Home > Internals, Java > Where did that Class come from?

Where did that Class come from?


Too many times I watched the logs trying to understand why I got the NoSuchMethodError. I sometimes get it with other derivatives of IncompatibleClassChangeError (AbstractMethodError, IllegalAccessError, InstantiationError, NoSuchFieldError) but NoSuchMethodError is the most common one.

The reason for this error is simple – the class you want to use is not the one being loaded at run time. This can be another version of the third party that finds its way to the classpath, or some old copy of your class. The problem is usually pin-pointing where it got from.

For that I have a simple solution – which unfortunately requires some code modification.
All you need to do is add these lines to your code (modify slightly) and you will get the result:

String className = classYouWantToFind.getName();
String classFileRelativePath = className.replace('.', '/') +  ".class";
java.net.URL classFileUrl = this.getClass().getClassLoader().getResource(classFileRelativePath);
System.out.println(className + " comes from [" + classFileUrl.toString() + "]");

This code asks the ClassLoader of the currently running object to find the .class representing the class you are looking for. Since the class loader searches for resources in the same order as it does for classes – it should find the correct one.

You can see a live example of this code on IDE One.

Note: You can always get this result by adding the -verbose:class VM argument – but this will get you verbose output of every class in the system.

Advertisements
Categories: Internals, Java Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: