简体   繁体   中英

Prevent ClassNotFoundException at runtime because of someone creating a java file with the same file name in a different JAR

I am getting ClassNotFound exception even though the class existed in my project.On further investigation,I found that another file with same file name ( Constants.java ) was present in another project and both these projects were present in my classpath(although with a different name).

So is there any way I can prevent that ClassNotFoundException at runtime because of someone including creating a similar file in a different project??

com.util.Constants.java  -  business-common.jar
com.util.Constants.java  -  reader.jar

My projects in classpath are:-

1) business-common.jar
2)reader.jar

The technical solution would be class loader separation, using something like OSGi to completely separate the classpath of your application's modules. OSGi is integrated in some Java EE Application Servers (eg Glassfish ) for separating the classpath of different EAR/WAR modules deployed on the same server.

If you don't want to introduce this extra complexity, you can easily solve it by using a dedicated package namespace for each module, eg com.reader.util.Constants vs com.business.util.Constants .

If there are two different classes with the same name in the same package, you are inviting trouble.

If there is a common utility package, there needs to be a package maintainer as well.

Are the two versions of the class really necessary, or is an accident that they are both included? Is it a Java EE application (WAR, EAR), which container is being used?

Often this situation is an accident, check this classpath troubleshooting tool JHades to know how many similar classpath duplicates exist in the project.

A standalone jar is available for generating command line reports, if there are problems starting the server there is support for runtime analysis.

This talk is great for further understanding the Java classpath and why these type of errors occur.

ClassNotFoundException means that one of the classloaders of your application cannot 'see' a class file for class Constants.

This does not mean that the class is not deployed on the server, only that a class loaded by a certain classloader needs this class but cannot find it.

JHades can be used to print the classloaders chain and query the classpath to better understand what is going on in these cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM