jeudi 14 novembre 2019

Using reflection to use a specific class constructor and create a new object

I have two classes.

public class Shape1 extends javafx.scene.shape.Path {

    public Shape1(PathElement... elements) {
        super(elements);
    }    
}

public class Shape2 extends javafx.scene.shape.Path {

    public Shape2(PathElement... elements) {
        super(elements);
    }    
}

They are not the same. They have different fields and methods, but I did not mention them for simplicity.

I create two arrays for each type of object and I only need to use one method to create them.

ArrayList<Shape1> first_shapes = create_array(50, 50, 100, 100, Class.forName("example3.Shape1"));
ArrayList<Shape2> second_shapes = create_array(50, 100, 100, 150, Class.forName("example3.Shape2"));

public static ArrayList create_array(int X1, int Y1, int X2, int Y2, Class my_class) {
    var shapes = new ArrayList<>();
    shapes.add(my_class.getConstructor(PathElement[].class).newInstance(new MoveTo(X1, Y1), new LineTo(X2, Y2)));
    ...
    return shapes;
}

The code has two problems.

  1. The class definition is inappropriate because it will not work when you change the class name or the package name and it has to be changed manually.

  2. Actually, it doesn't work at all because it crashes when you add an object to an array.

Strange is the fact that in the form above it will display an error.

wrong number of arguments

But if I use only one parameter,

shapes.add(my_class.getConstructor(PathElement[].class).newInstance(new MoveTo(X1, Y1)));

it will display an error.

argument type mismatch

It's the only solution to my problem. Otherwise I would have to change the whole algorithm.

Please help

Thank you





Aucun commentaire:

Enregistrer un commentaire