我有一个接口(interface),并且该接口(interface)有几个实现。现在我需要动态调用正确的 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);
不知道这样的做法是否正确?你能指导一下吗?
最佳答案
通过反射创建对象就像您所做的那样(除非错误处理,我假设您为了简洁而在此处省略了错误处理)。
但是创建对象后,为什么不简单地将其向下转换为 ITestInterface
并直接调用其方法呢?
ITestInterface obj = (ITestInterface) Class.forName(className).newInstance();
obj.customMethod(param1, param2);
(同样,这里省略了处理 ClassCastException
,但应该在生产代码中处理它。)
关于java - 动态调用实现方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6816725/