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.
>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);