Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new instance of object's class

Tags:

java

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?

like image 722
lawls Avatar asked Dec 30 '25 17:12

lawls


1 Answers

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.

like image 120
Sotirios Delimanolis Avatar answered Jan 01 '26 07:01

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!