Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring Java object given its type/class name as string

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

like image 515
Bruno Avatar asked Jan 14 '11 18:01

Bruno


2 Answers

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:

  • use 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(); 
    }
    
like image 108
Bozho Avatar answered Oct 23 '22 15:10

Bozho


If you have a default constructor:

SomeClass obj2 = (SomeClass) c.newInstance();
like image 44
Abdullah Jibaly Avatar answered Oct 23 '22 16:10

Abdullah Jibaly