动态调用Implementation方法

时间:2011-07-25 13:16:58

标签: java reflection

我有一个接口,该接口有几种实现方式。现在我需要动态调用正确的Implemented方法。

我从属性文件中获取Implementation Class名称。现在我必须使用反射来调用该方法。

请您建议最佳方法吗?

//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
  }
}

现在我需要使用Reflection调用customMethod(obj1,obj2)。我的班级名称为TestInterface

这就是我所做的。 我使用Class.forName(className)创建了一个TestInterface实例.newInstance();

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);

我不知道这是否是正确的方法?你能指导我吗?

1 个答案:

答案 0 :(得分:3)

通过反射创建对象就像你做的那样很好(除非错误处理,我假设你为了简洁而省略了这一点。)

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

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

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