开发者

Calling the Implementation method dynamically

开发者 https://www.devze.com 2023-03-22 13:58 出处:网络
I have an interface and there are couple of implementations for that Interface. Now I need to invoke the correct Implemented method dynamically.

I have an interface and there are couple of implementations for that Interface. Now I need to invoke the correct Implemented method dynamically.

I get the Implementation Class name from a property file. Now I have to invoke the method using reflection.

Could you please suggest the best approach to do it?

//This is my Interface.

public interface ITestInterface{
 开发者_高级运维   public CustomVO customMethod(CustomObj1 obj1,CustomObjec2 obj2);
}

//This class implements the above interface

public class TestInterface implements ITestInterface{
   public CustomVO customMethod(CustomObj1 obj1,CustomObjec2 obj2){

   //some logic
  }
}

Now I need to invoke customMethod(obj1,obj2) using Reflection. I've the class name of TestInterface.

This is what I did. I created an instance of TestInterface using Class.forName(className).newInstance();

Class[] paramTypes = new Class[ 2 ];
paramTypes [ 0 ] = CustomObj1.class;
paramTypes [ 1 ] = CustomObj2.class;
Object obj=Class.forName(className).newInstance();

Class.forName(className).getMethod( "customMethod", paramTypes ).invoke( obj, obj1,obj2);

I do not know if this is the correct way to do this? Could you please guide me?


Creating the object via reflection is fine as you did it (barring error handling, which I assume you omitted here for brevity).

But once you have the object created, why not simply downcast it to ITestInterface and call its method(s) directly?

ITestInterface obj = (ITestInterface) Class.forName(className).newInstance();
obj.customMethod(param1, param2);

(again, handling ClassCastException is omitted here, but it should be dealt with in production code.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号