简体   繁体   中英

Create new instance of object's class

Let's say I have an object called myCar that is an instance of 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.

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?

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 this for more details about Java's Reflection capabilities.

You just call newInstance( on the class object:

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

You need a default constructor and you must also remember that any exceptions get wrapped in an 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

Through reflection. Use this:

myCar.getClass().newInstance();

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]

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

In your code you have:

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

Object[] is indeed type of Object in 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

SOLUTION: Declare your Object arg as Object[] args and all should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM