get class of object and instantiate new instance
java, reflection, subclass
Solution
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.
Problem
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!