开发者

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 t开发者_运维知识库hat 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:

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


If you have a default constructor:

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


Like this:

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


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.


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.


Yeap, try:

That a = c.newInstance();


for me this worked:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜