user10714010
user10714010

Reputation: 935

How to instantiated a class from class type at run time?

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?

Upvotes: 0

Views: 56

Answers (2)

rgettman
rgettman

Reputation: 178263

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.

Upvotes: 2

Soutzikevich
Soutzikevich

Reputation: 1031

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

Upvotes: 1

Related Questions