Search code examples
javareflectionbytecodejavassist

How to remove a method from a compiled Java class/jar file?


I have a JAR file and there is a static class, I can't decompile it, it gets messed up. There is one method in it, that returns a class, that doesn't exist. No idea how, but I'm getting NoClassDefFoundError. Even though I'm not using that method, it still crashes. So I need to somehow just remove it and it should work fine. I know Reflection or Javassist could be used, but no idea how.

Note, that this is obviously not for production release, just some white-hat hacking.


Solution

  • I think you are mistaken: if that method would never be called, then the JVM would most likely not try to load that class.

    You see, the whole point of class loading - it happens lazy; when you load class X, and X needs Y, Z ... then Y and Z are only loaded when some code is executed that requires Y, Z to be loaded.

    In other words: that NoClassDefFound error actually tells you that something (maybe a static init somewhere in your JAR) is calling that method.

    Thus, the solution is not to "cut out" that one method (that would simply lead to another exception, like MethodNotFound!). Instead, you should try to create a dummy class to not run into that exception at all. Or: your JAR is missing at least one of its dependencies. You can try to resolve that dependency - maybe you can find the class somewhere, or, you "build" your own version of it (the second idea might be probably hard to get correct).