Overriding a method in statically created objects
Asked Answered
G

2

6

All,

Due to a bug in a library I'm using, I need to override the dispose() method on all objects extending a certain class and make it a NO-OP. I know that if I'm making new instances of the classes directly, this is easy to do:

layerManager = new LayerManagerLayer(wwd) {
    @Override
    public void dispose() {}
};

The problem is that a lot of the object instances I get are not directly constructed by my client code, but instead are created via static library method calls.

// Here I want to override the dispose method, but I cannot.
Layer l = ShapefileLoader.makeShapefileLayer(this.getClass().getResource("polylines10.shp"));

Is there a way I can inject my dispose method into that statically created object without modifying the original sourcecode?

Genesa answered 26/5, 2010 at 19:7 Comment(1)
"Is there a way I can [...] without modifying the original sourcecode?" - Lesson #1 - avoid using libraries where you don't at least have the option of modifying the source code to fix show-stopper bugs.Coady
S
5

If client compiles his own code, You can use AspectJ to inject Your around dispose() method. Other options are some bytecode modification tools like cglib. Look at this list: http://java-source.net/open-source/bytecode-libraries

Sharlenesharline answered 26/5, 2010 at 19:24 Comment(0)
S
1

You can use a byte code manipulation library like Javassist. You need to basically fetch the byte code of your LayerManagerLayer class and inject dispose method to it.

Shawanda answered 26/5, 2010 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.