Java 动态调用实现方法
我有一个接口,该接口有几个实现。现在我需要动态调用正确的实现方法 我从属性文件中获取实现类名。现在我必须使用反射调用该方法 你能建议最好的方法吗Java 动态调用实现方法,java,reflection,Java,Reflection,我有一个接口,该接口有几个实现。现在我需要动态调用正确的实现方法 我从属性文件中获取实现类名。现在我必须使用反射调用该方法 你能建议最好的方法吗 //This is my Interface. public interface ITestInterface{ public CustomVO customMethod(CustomObj1 obj1,CustomObjec2 obj2); } //This class implements the above interface pu
//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的实例
我不知道这样做是否正确?你能指导我吗?通过反射创建对象和你做的一样好(除了错误处理,我想你为了简洁起见省略了错误处理) 但是一旦创建了对象,为什么不直接将其向下转换到
ITestInterface
并直接调用其方法呢
ITestInterface obj = (ITestInterface) Class.forName(className).newInstance();
obj.customMethod(param1, param2);
(同样,这里省略了处理
ClassCastException
,但它应该在生产代码中处理。)通过反射创建对象与您所做的一样好(除了错误处理,我假设您为了简洁起见在这里省略了错误处理)
但是一旦创建了对象,为什么不直接将其向下转换到ITestInterface
并直接调用其方法呢
ITestInterface obj = (ITestInterface) Class.forName(className).newInstance();
obj.customMethod(param1, param2);
(同样,这里省略了处理
ClassCastException
,但它应该在生产代码中处理。)是的,这是你应该做的。是的,这是你应该做的。我建议使用classcasting而不是使用classcasting