Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a method in statically created objects

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?

like image 516
I82Much Avatar asked May 26 '10 19:05

I82Much


People also ask

Can you override a static method?

Can we override a static method? No, we cannot override static methods because method overriding is based on dynamic binding at runtime and the static methods are bonded using static binding at compile time. So, we cannot override static methods.

What is static method overriding?

Overloading is the mechanism of binding the method call with the method body dynamically based on the parameters passed to the method call. Static methods are bonded at compile time using static binding. Therefore, we cannot override static methods in Java.

Can we override the static method in Java?

Can we Override static methods in java? We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won't be any run-time polymorphism. Hence the answer is 'No'.

Can you declare an overridden method to be static if the original method is not static in C #?

No, they can't be overridden. They are associated with the class, not with an object. for the real use: you can call a static method without the class instance.


1 Answers

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

like image 148
Bartek Jablonski Avatar answered Oct 23 '22 05:10

Bartek Jablonski