3

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?

randomguy
  • 12,042
  • 16
  • 71
  • 101

5 Answers5

4

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.

Community
  • 1
  • 1
ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • `not with pretty much copying the class and replacing it there.` I assume you mean copying the library or at least the classes that internally call `Utils.getFile()`, right? Copying `Utils` wouldn't help much. – Thomas Jan 22 '12 at 08:04
  • @Thomas - correct. (I was assuming that all calls to `.getFile()` were only called by other methods in `Utils`. If this is not the case, none of these options - including a wrapper class - will work. – ziesemer Jan 22 '12 at 08:06
2

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

Luis
  • 1,294
  • 7
  • 9
1

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) {
    }
}
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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() ..

JustBeingHelpful
  • 18,332
  • 38
  • 160
  • 245
  • 1
    JAD seems to be quite old, AFAIK the most complete free decompiler is [JD](http://java.decompiler.free.fr/). - You also decompile to _.java_ files, not to _.jar_ files :) – Thomas Jan 22 '12 at 08:11
  • ah, thanks :-) .. I am a .NET developer now, so I haven't used Java since 2005 – JustBeingHelpful Jan 22 '12 at 08:11
0

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.

Community
  • 1
  • 1
Christian Neverdal
  • 5,655
  • 6
  • 38
  • 93