Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get class of object and instantiate new instance

I'm hoping to do something like:

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

In other words, I know what the superclass of varCopy will be at compile time, but I'm not sure which subclass will be instantiated. Is there a way to do this in Java?

Thanks!

like image 661
mfsiega Avatar asked Dec 26 '22 05:12

mfsiega


1 Answers

You could do something along these lines.

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

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

like image 65
Kal Avatar answered Jan 11 '23 23:01

Kal