创建对象类的新实例

law*_*wls 2 java

假设我有一个名为myCar的对象,它是Car的一个实例.

myCar = new Car();
Run Code Online (Sandbox Code Playgroud)

如何根据对象创建该类的新实例?假设我不知道myCar是从哪个类创建的.

otherObject = new myCar.getClass()(); // Just do demonstrate what I mean (I know this doesn't work)
Run Code Online (Sandbox Code Playgroud)

UPDATE

public class MyClass {
    public MyClass(int x, int y, Team team) { }
    public MyClass() { }
}

Object arg = new Object[] {2, 2, Game.team[0]};

try {
    Constructor ctor = assignedObject.getClass().getDeclaredConstructor(int.class, int.class, Team.class);
    ctor.setAccessible(true);
    GameObject obj = (GameObject) ctor.newInstance(arg);

} catch (InstantiationException x) {
    x.printStackTrace();
} catch (IllegalAccessException x) {
    x.printStackTrace();
} catch (InvocationTargetException x) {
    x.printStackTrace();
} catch (NoSuchMethodException x) {
    x.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

java.lang.IllegalArgumentException: wrong number of arguments
Run Code Online (Sandbox Code Playgroud)

getDeclaredConstructor()工作并找到我的构造函数有三个args,但newInstance(arg)由于某种原因不起作用,它说"错误的参数数量".知道为什么吗?

Sot*_*lis 15

随着反思

otherObject = myCar.getClass().newInstance();
Run Code Online (Sandbox Code Playgroud)

假设你的类有一个默认的构造函数.您可以使用非默认(空)构造函数执行更高级的操作

Constructor[] constructors = myCar.getClass().getConstructors();
Run Code Online (Sandbox Code Playgroud)

并选择你想要的那个.

阅读本文,了解有关Java反射功能的更多详细信息.