Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug NoSuchMethodError exception?

I am running the following code

package test.commons;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Try_FileUtilsWrite {

    public static void main(String[] args) throws IOException {
        System.out.println(FileUtils.class.getClassLoader());
        FileUtils.write(new File("output.txt"), "Hello world");
    }

}

and getting

Exception in thread "main" java.lang.NoSuchMethodError: org.apache.commons.io.FileUtils.write(Ljava/io/File;Ljava/lang/CharSequence;)V
    at test.commons.Try_FileUtilsWrite.main(Try_FileUtilsWrite.java:12)

apparently, an old version of commons io used somewhere. But I don't see it in the project.

Is it possible to know the path to class file at runtime?

like image 947
Suzan Cioc Avatar asked Apr 06 '15 15:04

Suzan Cioc


People also ask

What is nosuchmethoderror in Java?

- GeeksforGeeks How to Solve java.lang.NoSuchMethodError in Java? A java.lang.NoSuchMethodError as the name suggests, is a runtime error in Java which occurs when a method is called that exists at compile-time, but does not exist at runtime.

What is the difference between Nosuch method and nosuchmethodexception?

NoSuchMethodException is related to NoSuchMethodError, but occurs in another context. While a NoSuchMethodError occurs when some JAR file has a different version at runtime that it had at compile time, a NoSuchMethodException occurs during reflection when we try to access a method that does not exist.

What is the root cause of nosuchmethoderror?

The potential root cause for a NoSuchMethodError is that one of the libraries we use in our project had a breaking change from one version to the next. This breaking change removed a method from the code of that library.

What is NoClassDefFoundError instead of nosuchmethoderror?

Instead of the NoClassDefFoundError, a NoSuchMethodError will occur if we migrate to JUnit 5.4.0. 3. Understanding and Fixing the Error As illustrated in the previous section, we ended up with a NoClassDefFoundError when we tried to migrate our JUnit version from 5.3.2 to 5.7.1.


1 Answers

Yes you can use that Classloader to get the resource from which the class is loaded:

ClassLoader classLoader = FileUtils.class.getClassLoader();

URL resource = classLoader.getResource("org/apache/commons/io/FileUtils.class");
System.out.println(resource);

Sample output:

jar:file:/D:/maven_repository/commons-io/commons-io/2.0.1/commons-io-2.0.1.jar!/org/apache/commons/io/FileUtils.class

like image 79
M A Avatar answered Sep 29 '22 12:09

M A