lawls lawls - 1 year ago 71
Java Question

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)


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

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

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

} catch (InstantiationException x) {
} catch (IllegalAccessException x) {
} catch (InvocationTargetException x) {
} catch (NoSuchMethodException x) {

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download