【问题标题】:Calling the Implementation method dynamically动态调用实现方法
【发布时间】: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


【解决方案1】:

通过反射创建对象就像你做的那样(除非错误处理,为了简洁起见,我假设你在这里省略了)。

但是一旦你创建了对象,为什么不简单地将其转换为ITestInterface 并直接调用它的方法呢?

ITestInterface obj = (ITestInterface) Class.forName(className).newInstance();
obj.customMethod(param1, param2);

(同样,这里省略了处理ClassCastException,但应该在生产代码中处理。)

【讨论】:

  • 我建议使用Class<? extends ITestInterface> concreteClass = Class.forName(...).asSubclass(ITestInterface.class),而不是向下转换。然后,当您调用 newInstance() 时,您将不需要进行任何转换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-08-21
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2016-01-20
相关资源
最近更新 更多