Get an object class and instantiate a new instance

I hope to do something like:

SubClass c = var.getClass(); SuperClass varCopy = new SubClass(); 

In other words, I know that the superClass varCopy will be at compile time, but I'm not sure which subclass will be created. Is there any way to do this in Java?

Thanks!

+4
source share
1 answer

You can do something in this direction.

 Class<? extends SuperClass> clazz = var.getClass(); SuperClass varCopy = clazz.newInstance(); 

Note that clazz.newInstance() will throw an IllegalAccessException if it does not have an empty default constructor.

+9
source

All Articles