mercredi 11 janvier 2017

Is it possible to subclass a retrieved class via Java reflection

Is it possible to subclass a retrieved class via Java reflection? I'm trying to change the implementation of a method of an already loaded class. I know there is no way to do it via regular reflection methods. But I was wondering if it is possible by subclassing the retrieved class, such as:

final Class cls = classLoader.loadClass(className);
Object newRemoteInstance = new cls() {
    @Override
    public void saySth() {
         System.out.println("changed");
    }
}

instead of retrieving the exact same implementation with

cls.newInstance();

And then copying the fields of the already loaded class into the newly created instance and further using this new instance instead of the already loaded one. The class that is to change is not available, so I do have to use reflection.

Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire