[英]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. 换句话说,我知道varCopy的超类在编译时会是什么,但我不确定将实例化哪个子类。 Is there a way to do this in Java? 有没有办法在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. 请注意,如果clazz.newInstance()
没有默认的空构造函数,它将抛出IllegalAccessException。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.