vendredi 8 mai 2015

Java ClassCastException when invoking method

I am making a game engine and I'm currently working on the component-part of the program. I want the user to be able to provide a special render method to the components so therefore I am using reflection and some other stuff. As the title suggests, this throws a ClassCastException and I can't figure out why. Here's the code:

public class LComponent {
    public Vector pos, size;
    private Class renderClass = getClass();
    private Method renderMethod;

    public LComponent(Vector pos, Vector size) {
        try {
            renderMethod = renderClass.getDeclaredMethod("defaultRender",
                    Graphics.class);
            renderMethod.setAccessible(true);
        } catch (NoSuchMethodException | SecurityException e) {
            e.printStackTrace();
        }
    }

    public void render(Graphics g) {
        try {
            renderMethod.invoke(renderClass, g);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void defaultRender(Graphics g) {
        g.drawRect((int) pos.getX(), (int) pos.getY(), (int) size.getX(),
                (int) size.getY());
    }
}





Aucun commentaire:

Enregistrer un commentaire