ClassCircularityError thrown by ClassLoader.defineClass

Jim picture Jim · May 30, 2011 · Viewed 14k times · Source

I'm loading classes using a custom class loader. For the most part, everything works, but sometimes when I load particularly complex projects/libraries, I get a strange bug:

Exception in thread "main" java.lang.ClassCircularityError: 
  org/apache/commons/codec/binary/Hex
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:466)
    at my.custom.class.Loader.loadClass(...)

Looking at the Javadocs, I wouldn't expect defineClass to throw this particular error. org/apache/commons/codec/binary/Hex is the class I'm trying to load. It's almost as if defineClass wants a copy of the class before it'll define the class - which makes no sense to me.

Ideas?

Answer

Paŭlo Ebermann picture Paŭlo Ebermann · May 31, 2011

A ClassCircularityError is thrown when some class is a (indirect) superclass of itself, some interface (indirectly) extends itself or similar.

This should normally not occur as a well-behaved compiler will not produce such classes, but using different versions of a library (or using several libraries containing different versions of a class) could bring this problem.

Scan your libraries for double class names, in particular have a look if there are multiple versions of the mentioned org.apache.commons.codec.binary.Hex class.