Question


I have a problem with my constructor , I can't add parameter with my constructor

my code :

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 

my class: 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;
    }
}

My error : java.lang.NoSuchMethodException: So I don't understand why I can't add parameter with my constructor.

I have a prob with the method : getContructor(); If i make this :

Constructor<?> actionConstruct = actionClass.getConstructor(CreateFileAction.class);

I have this error :

java.lang.NoSuchMethodException: inteToM.CreateFileAction.<init>(inteToM.CreateFileAction)

If I make this :

Constructor<?> actionConstruct = actionClass.getConstructor(dto.m.CreateFile.class);

I have this :

java.lang.NoSuchMethodException: inteToM.CreateFileAction.<init>(dto.m.CreateFile)

Thanks for help.

Was it helpful?

Solution

Try this code. Main class

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

your dependent classes

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

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top