【发布时间】:2011-07-25 21:20:41
【问题描述】:
我有一个接口,该接口有几个实现。现在我需要动态调用正确的 Implemented 方法。
我从属性文件中获取了实现类名称。现在我必须使用反射来调用该方法。
您能建议最好的方法吗?
//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
}
}
现在我需要使用反射调用 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);
我不知道这是否是正确的方法?你能指导我吗?
【问题讨论】:
-
是的,这就是你应该这样做的方式。
标签: java reflection