java - 动态调用实现方法

标签 java reflection

我有一个接口(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/

相关文章:

java - 关联 Java 字段类型和泛型参数

c# - 如何通过反射调用非静态方法

c# - 未找到引用程序集 - 如何获取解决方案中包含的所有 DLL

java - 提高 Java 中字符串连接的性能

java - 当尝试启动应用程序时,spring-quartz 不会启动并显示错误消息?

java - 如何在java中实例化处理程序

c# - 如何在 C# 中查找调用方法的全名

.net - 如何获取属性覆盖属性?

Java 正在跳过一行(扫描仪中的字符串??)

java - SQL 语法中的 JDBC 问号