【发布时间】:2014-06-29 22:32:10
【问题描述】:
我的构造函数有问题,我的构造函数无法添加参数
我的代码:
import inteToM.CreateFileAction; // said not use import
import dto.m.CreateFile;
//...
// code
Class<?> dtoClass = Class.forName("dto.mToInte.CreateFile");
DtoM dto = (DtoM) JAXB.unmarshal(sr, dtoClass );
Class<?> actionClass = Class.forName("inteToM.CreateFileAction");
Constructor<?> actionConstruct = actionClass.getConstructor(); //dto.getClass()
ActionM aAction = (ActionIM) actionConstruct.newInstance(dto); // not working
ActionM bAction = (ActionIM) actionConstruct.newInstance(); // work
我的班级:CreateFichierAction
public class CreateFileAction {
import dto.mToInte.CreateFile;
public CreateFileAction () {
System.out.println(" constructor null");
}
public CreateFileAction (CreateFile file) {
System.out.println(" constructor not null");
this.file_c= file;
}
}
我的error : java.lang.NoSuchMethodException:
所以我不明白为什么我不能用我的构造函数添加参数。
我对该方法有疑问:getContructor();
如果我这样做:
Constructor<?> actionConstruct = actionClass.getConstructor(CreateFileAction.class);
我有这个错误:
java.lang.NoSuchMethodException: inteToM.CreateFileAction.<init>(inteToM.CreateFileAction)
如果我这样做:
Constructor<?> actionConstruct = actionClass.getConstructor(dto.m.CreateFile.class);
我有这个:
java.lang.NoSuchMethodException: inteToM.CreateFileAction.<init>(dto.m.CreateFile)
感谢您的帮助。
【问题讨论】:
-
为什么不使用真正的
.class来获取Class对象?如果您确实知道要反映在哪个课程中,那么您不需要forName。 -
我试试这个:ActionM aAction = (ActionIM) actionConstruct.newInstance(CreateFile.class); // 不起作用——我有同样的错误。
-
我的意思是你应该得到
actionClass和CreateFile.class而不是forName业务。 -
actionConstruct.newInstance(dto);这是一个DtoM dto但CreateFileAction需要一个CreateFile对象。 -
actionClass.getConstructor(dto.m.CreateFile.class);和actionClass.newInstance(dtoClass.newInstance())应该可以工作
标签: java class methods constructor