简体   繁体   中英

getConstructor Throws NoSuchMethodException in Java

I am very new to Java so this may be a dumb question, but I am trying to understand how to create a new instance of a class by getting the class from an existing instance (I think this is called reflection).

Currently I have a super class and several subclasses of it.

public abstract class SuperClazz {...}

public class SubClazz1 extends SuperClazz {...}

public class SubClazz2 extends SuperClazz {...}

I have an existing instance of one of these subclasses (declared only as a member of the super class, as I do not yet know which subclass it will belong to). I am trying to get whichever subclass this existing instance belongs to and make a new instance of that same subclass.

This is my setup:

private SuperClazz oldSubInstance;
private SuperClazz newSubInstance;

newSubInstance = oldSubInstance.getClass().getConstructor(String.class, char.class, int.class).newInstance("abc", 'e', 6);

Which throws NoSuchMethodException.

I am confused because I know SuperClazz has a constructor that takes in three parameters, a String, a char and an int. I have viewed answers here and here but have found that implementing the suggested fixes does not work, or that their issues do not apply to my situation.

Am I completely misunderstanding how getConstructor works?

You need to make sure that the all-args constructor exists in the children class(es).

The following example creates a newSubInstance :

// using Lombok annotations for brevity
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
abstract class SuperClazz {
    private String str;
    private char chr;
    private int x;

    // getters/setters/default and all-args constructors provided by Lombok
}


class SubClazz1 extends SuperClazz {
    public SubClazz1(String str, char c, int i) { // providing constructor in the child class
        super(str, c, i);
    }
}

// test
SuperClazz oldSubInstance = new SubClazz1("def", 'g', 10);
SuperClazz newSubInstance;

newSubInstance = oldSubInstance.getClass()
                               .getConstructor(String.class, char.class, int.class)
                               .newInstance("abc", 'e', 6);

System.out.println(newSubInstance);

output ( toString overridden at the base class level):

SuperClazz(str=abc, chr=e, x=6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM