lundi 27 juillet 2015

How to dynamically add new methods to a class in Java using reflection

I want to find a way to add dynamically a method to a class in java.

In this case I want to add the methods of a private object to the class and then if they are call, execute the method on this same object. Example :

public class A {
    private someType someObject;

    public A (someType someObject) {
        this.someObject = someObject;
        Method[] methods = someObject.getClass().getDeclaredMethods();

        for (Method method:methods) {
            //do something here to add the object method to the class like this
            Method newMethod;
            newMethod.setName("A."+method.getName());
            newMethod.setToDo("this.someObject."+method.getName());
            newMethod.create();
        }
    }
}

How to do something like this ? I already searched on stackoverflow and I don't find what I want.





Aucun commentaire:

Enregistrer un commentaire