2011-07-25 41 views
0

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

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

您能否建议最好的方法来做到这一点?

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

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

+1

好,没有工作? – biziclop

+0

是的,这就是你应该这样做的方式。 –

回答

3

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

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

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

(再次,处理ClassCastException这里省略,但它应该在生产代码来处理。)

+2

而不是downcasting我会建议使用'Class <?扩展ITestInterface> concreteClass = Class.forName(...)。asSubclass(ITestInterface.class)'。然后当你调用'newInstance()'时,你不需要进行任何转换。 –

+0

@Mark,感谢您的提示,这的确更好! –