Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Receive class type and argument and return instance

I know this maybe be a duplicate but i’ve been scouring through stack overflow but i’m still yet to find an answer.

What i want to do is accept a class type as argument and return an instance of that class. Here is what i’m trying to do

class A {

}

class B {

    /* 
    * Takes class type as argument and returns an instance of that class
    */
    public static Object createInstanceOfAnyClass(Class<?> klassType) {
        return new klassType();
    }
}

public class Main {
    public static void main(String[] args) {
        A a = B.createInstanceOfAnyClass(A);  // pass class(type) A and receive an instance of A
    }
}

Basically, after passing Class<A> as argument to B.createInstanceOfAnyClass, i should get an instance of class A.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a generic type parameter for the return type so you don’t need to cast the result from Object.

.getDeclaredConstructor().newInstance() can be used on a Class object to create an instance using the no-argument constructor.

public static <T> T createInstanceOfAnyClass(Class<T> klassType) {
    try {
        return klassType.getDeclaredConstructor().newInstance();
    } catch (ReflectiveOperationException e) {
        throw new RuntimeException(e); // or other handling
    }
}
// Usage:
A a = B.createInstanceOfAnyClass(A.class);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading