Java 创建对象类的新实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18241283/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:41:02  来源:igfitidea点击:

Create new instance of object's class

java

提问by lawls

Let's say I have an object called myCar that is an instance of Car.

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

myCar = new Car();

How would I do to create a new instance of that class based on the object? Let's say that I don't know which class myCar was created from.

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

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

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();
}

I get the following error:

我收到以下错误:

java.lang.IllegalArgumentException: wrong number of arguments

getDeclaredConstructor() works and finds my constructor with three args, but newInstance(arg) won't work for some reason, it says "wrong number of arguments". Any idea why?

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

采纳答案by Sotirios Delimanolis

With reflection

带反射

otherObject = myCar.getClass().newInstance();

Assuming your class has a default constructor. You can do more advanced operations with non default (empty) constructors

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

Constructor[] constructors = myCar.getClass().getConstructors();

And choose the one you want.

并选择你想要的。

Read through thisfor more details about Java's Reflection capabilities.

通读本文以了解有关 Java 反射功能的更多详细信息。

回答by nanofarad

You just call newInstance(on the class object:

您只需调用newInstance(类对象:

Car newCar=myCar.getClass().newInstance();

You need a default constructor and you must also remember that any exceptions get wrapped in an InvocationTargetException.

您需要一个默认构造函数,并且您还必须记住任何异常都包含在InvocationTargetException.

If the class does not have a default constructor, this is not possible without a non-reflective factory or constructor.

如果该类没有默认构造函数,则在没有非反射工厂或构造函数的情况下这是不可能的。

InstantiationException - if this Class represents an abstract class, an interface, an array class, a primitive type, or void; or if the class has no nullary constructor

InstantiationException - 如果这个 Class 表示一个抽象类、一个接口、一个数组类、一个基本类型或 void;或者如果该类没有空构造函数

回答by Kuldeep Jain

Through reflection. Use this:

通过反思。用这个:

myCar.getClass().newInstance();

回答by dantuch

Regarding your UPDATE/error - look here:

关于您的更新/错误 - 看这里:

public class DupaReflect {

    private String name;
    private int id;

    private DupaReflect(String name, int id) {
        super();
        this.name = name;
        this.id = id;
    }

    @Override
    public String toString() {
        return "DupaReflect [name=" + name + ", id=" + id + "]";
    }

    public static void main(String[] args) throws Exception {
        Object[] objects = new Object[] { "asd", 1 };
        DupaReflect dupa = DupaReflect.class.getDeclaredConstructor(String.class, int.class).newInstance(objects);
        System.out.println(dupa);
    }

}

This works and produces desired output. DupaReflect [name=asd, id=1]

这有效并产生所需的输出。 DupaReflect [name=asd, id=1]

Object[] objects = new Object[]{"asd", 1};- that's the reason why my code works and yours does not.

Object[] objects = new Object[]{"asd", 1};- 这就是为什么我的代码有效而你的无效的原因。

In your code you have:

在您的代码中,您有:

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

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

Object[]is indeed type of Objectin java, but this changes 3-element array of some objects into single object being that array. So you try to create a new object not with 3 arguments, but with 1, thus the exception is thrown

Object[]确实是Objectjava 中的类型,但这会将某些对象的 3 元素数组更改为作为该数组的单个对象。因此,您尝试创建一个不是带有 3 个参数而是带有 1 个参数的新对象,因此会引发异常

SOLUTION: Declare your Object argas Object[] argsand all should work.

解决方案:宣布你Object argObject[] args所有应该工作。