我有一个接口,并且该接口有几个实现。现在我需要动态地调用正确的实现方法。动态调用实现方法
我从属性文件中获取实现类的名称。现在我必须使用反射来调用该方法。
您能否建议最好的方法来做到这一点?
//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
}
}
现在我需要使用Reflection调用customMethod(obj1,obj2)。我的课程名称为TestInterface
。
这就是我所做的。我使用Class.forName(className).newInstance()创建了一个TestInterface的实例。
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);
我不知道这是否是这样做的正确方法?你能指导我吗?
好,没有工作? – biziclop
是的,这就是你应该这样做的方式。 –