Got a school-project in java, using Reflection, I managed to handle this topic except for dealing with a HashMap.
Say we have a Shape class, and polygons that extend Shape.
Every polygon inherits an ID and a name. Here's a short example for implementation with Triangle:
Class Shape{
private static int id_counter;
protected ID;
protected Shape(String name){
ID = id_counter;
id_counter++;
this.name = name;
}
}
Class Triangle {
{
public Triangle(Sting name, Point[] vertices)
{
super(name);
/* some operations to define Triangle vertices*/
}
public int getID()
{
return this.ID;
}
It's required to perform actions on the polygons by their ID only, therefore I used a HashMap called shapesHash:
HashMap <Integer, Shape> shapesHash = new HashMap <Integer, Shape>;
Things started to get tricky when I tried to create new shapes using Reflection. In Main void, I declared as follows (skipping the required try-catch wrap):
Class<? extends Shape> myClass = Class.forName("polygonName").asSubclass(Shape.class);
// String "polygonName" is given
Constructor<?> myConstructor = myClass.getDeclaredConstructor();
Object myObject = myConstructor.newInstance(name, points);
// String "name" and Points 'points' are given
Method myMethod = myClass.getMethod("getID");
Object result = myMethod.invoke(null);
shapesHash.put( (Integer) result, (Class<? extends Shape>) myClass);
The problem is that I tried to figure out what to put as a second argument,
instead of (Class<? extends Shape>)myClass
I tried many varieties of casting, and no casting at all - but didn't succeed (I get a compilation error).
What can I do in this situation?
Aucun commentaire:
Enregistrer un commentaire