Java object declaration, given its type / class name as a string

I was wondering if it is possible to declare a new object of a specific type in Java, given that I have this type represented as an object of a class.

For example, let's 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 this type. Something like that:

Class<c> my_new_var;

so my_new_var will then be a variable of the same type / class as obj1. This is directly related, I suppose, to whether it is possible to use a class object (or something related to this class object) as a type in the declaration of a new variable.

Is this possible or impossible, since Java is strongly typed?

Thanks in advance,

Bruno

+5
source share
7
YourType newObject = c.newInstance();

no-arg. .

, , Class . , , .

- , , , java . . :

  • Object, , .
  • . ( ):

    public static <T> T createNewInstance(T exampleInstance) {
       return (T) exampleInstance.getClass().newInstance(); 
    }
    
+2

:

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

Yeap, :

a = c.newInstance();

0

:

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

my_new_var Class<SomeClass>, obj1, SomeClass.

my_new_var.newInstance() , , obj1.

0

, :

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

no-arg ( ) SomeClass obj1.

, Class. - raw Class Class<?> , , newInstance() , Object.

0

:

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

All Articles