prob with getConstructor(parameter):java.lang.NoSuchMethodException:

时间:2014-05-12 14:01:45

标签: java class methods constructor


我的构造函数有问题,我无法使用构造函数添加参数

我的代码:

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)

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

试试这段代码。  主要课程

package com.sree;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.sree.test.CreateFile;

public class Test {
    public static void main(String[] args) throws SecurityException,
            NoSuchMethodException, IllegalArgumentException,
            InstantiationException, IllegalAccessException,
            InvocationTargetException {
        Constructor<CreateFileAction> action = CreateFileAction.class
                .getConstructor(CreateFile.class);
        CreateFile file = new CreateFile();
        System.out.println(action.newInstance(file));
        // System.out.println(action);
    }
}

您的受抚养人类

package com.sree;

import com.sree.test.CreateFile;

public class CreateFileAction {

    private CreateFile file_c;

    public CreateFileAction() {
        System.out.println(" constructor null");
    }

    public CreateFileAction(CreateFile file) {
        System.out.println(" constructor not null");
        this.file_c = file;
    }
}

package com.sree.test;

public class CreateFile {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}