Reputation: 432
I am using the getConstructors() method to pull the class's contructors. The class is in an abstract superclass reference, and I won't know which subclass is being called until the user decides. Here's what I have so far.
Weapon stickCopy = stick;
System.out.println(stick);
System.out.println(stickCopy);
Class <? extends Weapon> myClass = stick.getClass( );
System.out.println(myClass.getSimpleName( ));
Constructor<?>[] construct = myClass.getConstructors( );
for(Constructor<?> constructor: construct)
{
System.out.println(constructor);
}
try
{
stickCopy = (Weapon) construct[2].newInstance((stick));
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(stick);
System.out.println(stickCopy);
The Stick class is a subclass of the abstract Weapon class. I am trying to figure out the code for a deep copy from a Weapon reference, stored in a player object. Since Weapon is abstract, I can't call a copy constructor from it. In my Stick class, the copy constructor is the third constructor, and so I hard-coded 2 into the construct array in the try statement. If I change the stick class's constructors by, say, adding a new constructor in front of the copy constructor or reordering them, how can I find the position of the copy constructor at run-time?
Also, I have never used Generics before, so, if I am not following what are generally considered good programming practices, please correct me.
Upvotes: 2
Views: 310
Reputation: 2295
Costructor.getParameterTypes() tells you the types the parameters the constructor takes. So check for the one that takes an Object of the correct type.
Upvotes: 2
Reputation: 6675
If you use the version of getConstructor that takes arguments you can specify the constructor you want by its argument types. Presumably you'll want to pass either Stick.class or Weapon.class in:
Constructor constructor = myClass.getConstructor(myClass);
Upvotes: 5