Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
在 Ruby 中,我可以执行以下操作:
object2 = object1.class.new
我可以在 Java 中做同样的事情吗?这种模式称为反射吗?
你可以使用反射
Object object2 = object1.getClass().newInstance();
如果你知道 object1 的类型,你可以这样做
MyType object1 = ... MyType object2 = (MyType) object1.getClass().newInstance();