NoSuchMethodError를 어떻게 해결합니까?
나는군요 NoSuchMethodError
내 Java 프로그램을 실행할 때 오류가 발생했습니다. 무엇이 잘못되었으며 어떻게 해결합니까?
더 이상의 정보가 없으면 문제를 정확히 파악하기는 어렵지만 근본 원인은 메서드를 실행할 때 사용하고있는 것과 다른 버전의 메서드에 대해 클래스를 컴파일했을 가능성이 높습니다.
스택 추적보기 ... 라이브러리의 객체에서 메소드를 호출 할 때 예외가 발생하면 컴파일 및 실행시 별도의 버전의 라이브러리를 사용하는 것 같습니다. 두 곳 모두 올바른 버전인지 확인하십시오.
클래스가 인스턴스화 된 객체의 메소드 호출 할 때 예외가 나타나면 당신이 만든을 한 후 빌드 프로세스에 결함이있을 것으로 보인다. 컴파일 할 때 실제로 실행중인 클래스 파일이 업데이트되었는지 확인하십시오.
나는 당신의 문제를 겪고 있었고, 이것이 내가 고친 방법입니다. 다음 단계는 라이브러리를 추가하는 효과적인 방법입니다. 처음 두 단계를 올바르게 수행했지만 파일 시스템에서 ".jar"파일을 이클립스 프로젝트의 "lib"폴더로 직접 드래그하여 마지막 단계를 수행하지 않았습니다. 또한 빌드 경로와 "lib"폴더에서 이전 버전의 라이브러리를 제거해야했습니다.
1 단계-.jar을 추가하여 경로 작성
2 단계-소스 및 javadoc 연결 (선택 사항)
3 단계-실제로 .jar 파일을 "lib"폴더로 드래그 (선택 사항 아님)
리플렉션의 경우 NoSuchMethodException
, 비 반사 코드의 경우을 얻습니다 NoSuchMethodError
. 나는 서로 대면 할 때 매우 다른 곳을 찾는 경향이 있습니다.
JVM 매개 변수를 변경할 수있는 액세스 권한이있는 경우 자세한 출력을 추가하면 어떤 JAR에서 어떤 클래스가로드되는지 확인할 수 있습니다.
java -verbose:class <other args>
프로그램이 실행될 때 JVM은 다음과 같은 표준 출력 정보로 덤프해야합니다.
...
[파일에서로드 된 junit.framework.Assert : / C : /Program%20Files/junit3.8.2/junit.jar]
...
이것은 일반적으로 java 파일이 클래스 파일보다 최신 일 때 java 파일 만 컴파일하는 Apache Ant 와 같은 빌드 시스템을 사용할 때 발생 합니다. 메소드 서명이 변경되고 클래스가 이전 버전을 사용하는 경우 올바르게 컴파일되지 않을 수 있습니다. 일반적인 수정은 전체 재 구축 (보통 "ant clean", "ant")을 수행하는 것입니다.
때로는 한 버전의 라이브러리에 대해 컴파일 할 때 다른 버전에 대해서는 실행될 때이 문제가 발생할 수 있습니다.
Maven 또는 다른 프레임 워크를 사용하는 경우이 오류가 거의 무작위로 발생하면 다음과 같이 새로 설치하십시오.
clean install
이것은 객체를 작성했고 객체에 메소드가 있음을 알고있는 경우 특히 효과적입니다. 나를 위해 일했다.
리플렉션을 사용한 결과 일 수도 있습니다. 클래스에 반영하는 코드가 있고 이름으로 메소드를 추출하는 경우 (예 : with Class.getDeclaredMethod("someMethodName", .....)
) 리팩터링 중과 같이 메소드 이름이 변경 될 때마다 매개 변수를 리플렉션 메소드로 업데이트해야합니다. 새로운 메소드 서명, 또는 getDeclaredMethod
호출은를 던집니다 NoSuchMethodException
.
이것이 원인 인 경우 스택 추적은 리플렉션 메소드가 호출 된 지점을 표시해야하며 실제 메소드 서명과 일치하도록 매개 변수를 업데이트하기 만하면됩니다.
내 경험상 이것은 개인 메소드 / 필드를 단위로 테스트하고 TestUtilities
클래스를 사용하여 테스트 확인을 위해 필드를 추출 할 때 가끔 발생 합니다. 일반적으로 단위 테스트를 염두에두고 설계되지 않은 레거시 코드를 사용합니다.
If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.
e.g.
- tomcat/common/lib
- mywebapp/WEB-INF/lib
These problems are caused by the use of the same object at the same two classes. Objects used does not contain new method has been added that the new object class contains.
ex:
filenotnull=/DayMoreConfig.conf
16-07-2015 05:02:10:ussdgw-1: Open TCP/IP connection to SMSC: 10.149.96.66 at 2775
16-07-2015 05:02:10:ussdgw-1: Bind request: (bindreq: (pdu: 0 9 0 [1]) 900 900 GEN 52 (addrrang: 0 0 2000) )
Exception in thread "main" java.lang.NoSuchMethodError: gateway.smpp.PDUEventListener.<init>(Lgateway/smpp/USSDClient;)V
at gateway.smpp.USSDClient.bind(USSDClient.java:139)
at gateway.USSDGW.initSmppConnection(USSDGW.java:274)
at gateway.USSDGW.<init>(USSDGW.java:184)
at com.vinaphone.app.ttn.USSDDayMore.main(USSDDayMore.java:40)
-bash-3.00$
These problems are caused by the concomitant 02 similar class (1 in src, 1 in jar file here is gateway.jar)
It means the respective method is not present in the class:
- If you are using jar then decompile and check if the respective version of jar have proper class.
- Check if you have compiled proper class from your source.
For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again
I have just solved this error by restarting my Eclipse and run the applcation. The reason for my case may because I replace my source files without closing my project or Eclipse. Which caused different version of classes I was using.
Try this way: remove all .class files under your project directories (and, of course, all subdirectories). Rebuild.
Sometimes mvn clean
(if you are using maven) does not clean .class files manually created by javac
. And those old files contain old signatures, leading to NoSuchMethodError
.
Just adding to existing answers. I was facing this issue with tomcat in eclipse. I had changed one class and did following steps,
Cleaned and built the project in eclpise
mvn clean install
- Restarted tomcat
Still I was facing same error. Then I cleaned tomcat, cleaned tomcat working directory and restarted server and my issue is gone. Hope this helps someone
To answer the original question. According to java docs here:
"NoSuchMethodError" Thrown if an application tries to call a specified method of a class (either static or instance), and that class no longer has a definition of that method.
Normally, this error is caught by the compiler; this error can only occur at run time if the definition of a class has incompatibly changed.
- If it happens in the run time, check the class containing the method is in class path.
- Check if you have added new version of JAR and the method is compatible.
I fixed this problem in Eclipse by renaming a Junit test file.
In my Eclipse work space I have an App project and a Test project.
The Test project has the App project as a required project on the build path.
Started getting the NoSuchMethodError.
Then I realized the class in the Test project had the same name as the class in the App project.
App/
src/
com.example/
Projection.java
Test/
src/
com.example/
Projection.java
After renaming the Test to the correct name "ProjectionTest.java" the exception went away.
I ran into a similar problem when I was changing method signatures in my application. Cleaning and rebuilding my project resolved the "NoSuchMethodError".
Above answer explains very well ..just to add one thing If you are using using eclipse use ctrl+shift+T and enter package structure of class (e.g. : gateway.smpp.PDUEventListener ), you will find all jars/projects where it's present. Remove unnecessary jars from classpath or add above in class path. Now it will pick up correct one.
I ran into similar issue.
Caused by: java.lang.NoSuchMethodError: com.abc.Employee.getEmpId()I
Finally I identified the root cause was changing the data type of variable.
Employee.java
--> Contains the variable (EmpId
) whose Data Type has been changed fromint
toString
.ReportGeneration.java
--> Retrieves the value using the getter,getEmpId()
.
We are supposed to rebundle the jar by including only the modified classes. As there was no change in ReportGeneration.java
I was only including the Employee.class
in Jar file. I had to include the ReportGeneration.class
file in the jar to solve the issue.
I've had the same problem. This is also caused when there is an ambiguity in classes. My program was trying to invoke a method which was present in two JAR files present in the same location / class path. Delete one JAR file or execute your code such that only one JAR file is used. Check that you are not using same JAR or different versions of the same JAR that contain the same class.
DISP_E_EXCEPTION [step] [] [Z-JAVA-105 Java exception java.lang.NoSuchMethodError(com.example.yourmethod)]
Most of the times java.lang.NoSuchMethodError is caught be compiler but sometimes it can occur at runtime. If this error occurs at runtime then the only reason could be the change in the class structure that made it incompatible.
Best Explanation: https://www.journaldev.com/14538/java-lang-nosuchmethoderror
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.
The problem in my case was having two versions of the same library in the build path. The older version of the library didn't have the function, and newer one did.
I had a similar problem with my Gradle Project using Intelij. I solved it by deleting the .gradle (see screenshot below) Package and rebuilding the Project. .gradle Package
NoSuchMethodError : I have spend couple of hours fixing this issue, finally fixed it by just renaming package name , clean and build ... Try clean build first if it doesn't works try renaming the class name or package name and clean build...it should be fixed. Good luck.
I had the same error:
Exception in thread "main" java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonGenerator.writeStartObject(Ljava/lang/Object;)V
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:151)
at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:292)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3681)
at com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:3057)
To solve it I checked, firstly, Module Dependency Diagram (click in your POM the combination -> Ctrl+Alt+Shift+U
or right click in your POM -> Maven -> Show dependencies
) to understand where exactly was the conflict between libraries (Intelij IDEA). In my particular case, I had different versions of Jackson dependencies.
1) So, I added directly in my POM of the project explicitly the highest version - 2.8.7 of these two.
In properties:
<jackson.version>2.8.7</jackson.version>
And as dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
2) But also it can be solved using Dependency Exclusions.
By the same principle as below in example:
<dependency>
<groupId>group-a</groupId>
<artifactId>artifact-a</artifactId>
<version>1.0</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</exclusion>
</exclusions>
</dependency>
Dependency with unwanted version will be excluded from your project.
내 경우에는 내가 멀티 모듈 프로젝트를했고 같은 시나리오였다 com.xyz.TestClass
모듈에 있었다 A
뿐만 아니라 모듈 B
과 모듈은 A
모듈에 의존했다 B
. 따라서 어셈블리 항아리를 만드는 동안 호출 된 메서드가없는 경우 하나의 버전의 클래스 만 유지되었다고 생각 NoSuchMethodError
합니다. 런타임 예외가 발생했지만 컴파일은 괜찮습니다.
관련 : https://reflectoring.io/nosuchmethod/
파일 이름이 기본 메소드를 포함하는 클래스 이름과 다른 경우이 오류가 발생할 수 있습니다.
참고 URL : https://stackoverflow.com/questions/35186/how-do-i-fix-a-nosuchmethoderror
'IT' 카테고리의 다른 글
Bash에서 길이가 0이 아닌 문자열을 테스트하십시오. [-n "$ var"] 또는 [ "$ var"] (0) | 2020.06.04 |
---|---|
C ++에서 다중 상속을 피해야하는 이유는 무엇입니까? (0) | 2020.06.03 |
Django 템플릿에서 배열 요소에 액세스하는 방법은 무엇입니까? (0) | 2020.06.03 |
원인 : buildOutput.apkData가 널이 아니어야합니다. (0) | 2020.06.03 |
하단 점이있는 Android ViewPager (0) | 2020.06.03 |