Reputation: 2872
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!
Upvotes: 6
Views: 7613
Reputation: 24910
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.
Upvotes: 11