如何利用java反射构造一个类,使之实现一个接口和一些功能

由于做工具包需要泛化,现需要通过java的反射API实现题述要求,详述如下:
已知类A和接口C
public class A {
public void func(){}
}

public interface C {
public void exe();
}

现需要通过反射机制生成如下所示的类B
public class B implements C {
private A a;

public void exe() {
a.func();
}
}

其中,B中的属性A是从配置文件中读取的,也就是说,B中的属性还可能是除了A外的其他类的实例,并且在exe中调用的A方法也是在配置文件中指明的。

想问达人们,这种要求能够实现吗?要是现有java反射机制不行的话,有没有什么工具可以实现?

第1个回答  推荐于2016-04-07
可以实现,很方便。我去找个例子贴给你

Class daoFactoryClass = Class.forName(daoName);
//daoName是DAOFactory实现类的名字

// types of the constructor arguments
Class[] constrArgs = {Properties.class};

Object[] args = {daoProps};
//daoProps是Properties类型,它的内容来自一个配置文件
// get Constructor of this class with matching parameter types
Constructor<IDAOFactory> constructor = daoFactoryClass.getConstructor(constrArgs);

this.factory = constructor.newInstance(args);本回答被提问者采纳
相似回答