I was wondering whether it is possible to declare a new object of some given type in Java, given that I have that type represented as a Class object.
For instance, let us say that I have
SomeClass obj1;
Class c = obj1.getClass();
Now I would like to take "c" and use it to declare a new object of that type. Something along these lines:
Class<c> my_new_var;
such that my_new_var would then be a variable of same type/class as obj1. This is directly related, I guess, to whether we can use a Class object (or something related to that Class object) as a type in the declaration of a new variable.
Is that possible, or impossible since Java is strongly-typed?
Thanks in advance,
Bruno
YourType newObject = c.newInstance();
But you need to have a no-arg constructor. Otherwise you'd have to do more reflection.
Note that there is no need to cast if your Class
is parameterized. If it is not, as in your code, you'd need a cast.
To your 2nd question - no, it is not possible to declare a variable of a dynamic type, because yes, java is statically typed. You must define the type of a variable at compile time. In the above example you can:
Object
, if you don't know the type, because it is the superclass of all objects.use generics. For example (with exception handling omitted):
public static <T> T createNewInstance(T exampleInstance) {
return (T) exampleInstance.getClass().newInstance();
}
If you have a default constructor:
SomeClass obj2 = (SomeClass) c.newInstance();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With