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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With