Create new instance of object's class
java
Solution
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.
Problem
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?