Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
manypancakes Avatar asked May 25 '26 15:05

manypancakes


1 Answers

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)
like image 74
Nowhere Man Avatar answered May 27 '26 03:05

Nowhere Man



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!