0

Consider the following attempt that doesn't quite work

public void createClass() {
    try {
        MyClass b = (MyClass)getMyClassType().newInstance();
    } catch(Exception e) {
        e.printStackTrace();
    }
 }

public Class<?> getMyClassType() {
    MyClass a = new MyClass(1);
    return a.getClass();
}


public class MyClass {
    private int k = 0;
    public MyClass(int t) {
        k = t;
    }

}

The above gets

Caused by: java.lang.NoSuchMethodException

I am not quite sure why it doesn't work.

Essentially I want to be able to create class from class type, preferably something like this

 Map<String, ClassType> a = new HashMap<>()

 a.get("myClassName").createClassInstanceFromClassType(constructorParam1);

Is the above possible in java?

user10714010
  • 865
  • 2
  • 13
  • 20
  • Is this what you're looking for? https://stackoverflow.com/questions/6094575/creating-an-instance-using-the-class-name-and-calling-constructor – John Humphreys Dec 19 '18 at 19:57
  • 2
    `Class.newInstance()` attempts to use the no-argument constructor which `MyClass` doesn't have. – Slaw Dec 19 '18 at 19:57
  • This may be helpful: https://stackoverflow.com/questions/3671649/java-newinstance-of-class-that-has-no-default-constructor – John McClane Dec 19 '18 at 20:00

2 Answers2

2

The Class.newInstance method creates a new instance of the class using the no-argument constructor. However, MyClass doesn't have a no-argument constructor; it has only the one-argument constructor you gave it. That is why you got a NoSuchMethodException. Besides, the method Class.newInstance has been deprecated since Java 9.

Use the getDeclaredConstructor method to pass in the parameter types expected in the constructor to find. Then you can pass in the argument to the constructor as an argument to newInstance.

MyClass b = (MyClass) getMyClassType().getDeclaredConstructor(int.class).newInstance(1);

Additionally, you can change the return type of getMyClassType to Class<? extends MyClass>. This allows you to remove the cast to MyClass above.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

What you are looking for, is called a constructor.

If a class does not have a constructor declared, then the JVM will implicitly create one for you.

What you are trying to do, is quite simply achieved by using the new keyword.

In its very own essence, this is what you want:

class MyClass{

    MyClass(){
     //your implementation
    }
}



class AnotherClass{
    public static void main(String[] args){
        MyClass myClass = new MyClass();
    }
}
Soutzikevich
  • 991
  • 3
  • 13
  • 29