How do I fix a NoSuchMethodError?

前端 未结 29 2938
孤独总比滥情好
孤独总比滥情好 2020-11-21 05:08

I\'m getting a NoSuchMethodError error when running my Java program. What\'s wrong and how do I fix it?

29条回答
  •  情深已故
    2020-11-21 06:01

    I've encountered this error too.

    My problem was that I've changed a method's signature, something like

    void invest(Currency money){...}
    

    into

    void invest(Euro money){...}
    

    This method was invoked from a context similar to

    public static void main(String args[]) {
        Bank myBank = new Bank();
    
        Euro capital = new Euro();
        myBank.invest(capital);
    }
    

    The compiler was silent with regard to warnings/ errors, as capital is both Currency as well as Euro.

    The problem appeared due to the fact that I only compiled the class in which the method was defined - Bank, but not the class from which the method is being called from, which contains the main() method.

    This issue is not something you might encounter too often, as most frequently the project is rebuilt mannually or a Build action is triggered automatically, instead of just compiling the one modified class.

    My usecase was that I generated a .jar file which was to be used as a hotfix, that did not contain the App.class as this was not modified. It made sense to me not to include it as I kept the initial argument's base class trough inheritance.

    The thing is, when you compile a class, the resulting bytecode is kind of static, in other words, it's a hard-reference.

    The original disassembled bytecode (generated with the javap tool) looks like this:

     #7 = Methodref          #2.#22         // Bank.invest:(LCurrency;)V
    

    After the ClassLoader loads the new compiled Bank.class, it will not find such a method, it appears as if it was removed and not changed, thus the named error.

    Hope this helps.

提交回复
热议问题