How to get java.lang.NoSuchMethodError

独自空忆成欢 提交于 2019-12-21 17:28:34

问题


Introduction:

There are many questions as How to fix java.lang.NoSuchMethodError on SO.

As I can see, the simplest way to get this error, is to make a class

class MyClass {} // no methods at all, for instance

without properly defined main method, compile it and run:

java MyClass

Exception emerges:

Exception in thread "main" java.lang.NoSuchMethodError: main

But this example is too simple.

The question:

Could anyone provide a simple code, which

  1. Consists of two, maximum three classes (if you can show that more classes are needed - then you are welcome);
  2. Contains properly defined main method;
  3. Running of the class with that main method, leads to exception with java.lang.NoSuchMethodError.

回答1:


NoSuchMethodError happens if one class expects a method in another class (and was compiled with that method in place), but at runtime the other class does not have that method. So you need to:

  • create two classes, one of which calls a method on the other
  • compile the two classes
  • then remove the invoked method from the 2nd class, and compile the 2nd class only

Then, if you run the first class (with main method), it will throw that error when trying to call the method on the 2nd class (the method no longer exists)

This example would rarely happen in the real world though. Here are some real cases when the error occurs:

  • You are using a 3rd party library (jar) that depends on another jar. However you are having incompatible versions of those jars, and the 1st one tries to invoke a method on a class in the 2nd jar that does not exist anymore/yet.
  • Your compile-time and runtime classpaths differ - you have compiled your code against a version of some library (that can also be the JDK itself), but your runtime is having other versions
  • You have a multi-module project. Your IDE "links" the project at compile-time, so any changes is seen immediately. But when you build you forget to compile one of the modules (where you have added a method), so at runtime it is using the old version.



回答2:


Create a class file from a class which calls java.util.Properties.load(Reader) in its main method with some Java version >= 1.6.xxxx.

Attempt to execute this class using some Java version < 1.6.xxxx

Reason: java.util.Properties.load(Reader) was introduced in Java 6. It is being called, but does not exist in this version of Java.

This applies similarly to all methods introduced to the default language libraries in updates.



来源:https://stackoverflow.com/questions/6798767/how-to-get-java-lang-nosuchmethoderror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!