jeudi 15 octobre 2020

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?





Aucun commentaire:

Enregistrer un commentaire