randomguy
randomguy

Reputation: 12252

Is it possible to replace a public static method in Java?

I'm using a library that has a public static method getFile() defined in the Utils class. The library uses Utils.getFile() a lot internally, but this method is not very well implemented.

I was wondering if it's possible to somehow override Utils.getFile() so it would use my implementation instead?

Upvotes: 3

Views: 3914

Answers (5)

Peter Lawrey
Peter Lawrey

Reputation: 533530

You only option is to replace the class. You can compile a different version and make it earlier in the class path or replace the original copy.

Java doesn't support polymorphism for static methods (you can hide but not override a static method) For this reason, Utility classes are often made final to make this clear. To implement this I use an enum with no instances.

public enum Util {;
    public static ReturnType method(ParameterTypes... args) {
    }
}

Upvotes: 1

JustBeingHelpful
JustBeingHelpful

Reputation: 18980

Fix the code by getting the source code of the library and recreate the jar file. Try using JAD (along with FrontEndPlus) to decompile the .class files to .java files.

If the calls are in your code, then you can use your fully qualified Utils class name prefixing the method. Example: {your namespace}.Utils.getFile() ..

Upvotes: 0

Christian Neverdal
Christian Neverdal

Reputation: 5375

Unfortunately, no. This answer on StackOverflow explains why that is. You would need to create a wrapper class. This is the case for most languages, again explained in the link.

Upvotes: 0

ziesemer
ziesemer

Reputation: 28697

No - not with pretty much copying the class and replacing it there. Otherwise, a better alternative may be +1 for Christian's comment: Why doesn't Java allow overriding of static methods?

If it was non-static and the method wasn't private or final, you could subclass the class, provide your own overridden method, and use that.

Upvotes: 4

Luis
Luis

Reputation: 1294

No, you can't override it. Static methods have these kinds of problems, for instance, when writing unit tests.

Upvotes: 2

Related Questions