Bruno
Bruno

Reputation: 61

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

Upvotes: 6

Views: 7221

Answers (7)

vinay
vinay

Reputation: 1121

for me this worked:

Object innerObj = classObj.getClass().newInstance();

Upvotes: 0

OscarRyz
OscarRyz

Reputation: 199224

Yeap, try:

That a = c.newInstance();

Upvotes: 0

Bozho
Bozho

Reputation: 597106

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

Upvotes: 2

ColinD
ColinD

Reputation: 110054

Well, you could do this:

SomeClass obj1 = ...
Class<? extends SomeClass> c = obj1.getClass();
SomeClass obj2 = c.newInstance();

This requires a no-arg constructor on whatever subclass (if any) of SomeClass obj1 actually is.

However, this only works because you know the type of the Class object in question. Given some arbitrary raw Class or Class<?> object, you would not know what type of object newInstance() would return and you would only be able to declare that instance as an Object.

Upvotes: 0

Axel Fontaine
Axel Fontaine

Reputation: 35169

my_new_var would be of type Class<SomeClass> , which is not the same as obj1 which is of type SomeClass.

However my_new_var.newInstance() does give you a new object which is of the same type as obj1.

Upvotes: 0

Abdullah Jibaly
Abdullah Jibaly

Reputation: 54790

If you have a default constructor:

SomeClass obj2 = (SomeClass) c.newInstance();

Upvotes: 1

Matt
Matt

Reputation: 1422

Like this:

Class c  = Class.forName("com.xyzws.SomeClass"); 
Object a = c.newInstance();

Upvotes: 0

Related Questions