mburke13
mburke13

Reputation: 500

NoClassDefFoundError on ClassLoader.defineClass (wrong name)

I have a class file that I am reading the bytes from and defining into a Class object via a reflective call to ClassLoader.defineClass.

The NoClassDefFoundError message that I'm receiving is:

Caused by: java.lang.NoClassDefFoundError: com/foo/sub/Foo (wrong name: com.foo.sub.Foo)

The class file was compiled with the package "com.foo.sub" so the fully qualified name of the class would be "com.foo.sub.Foo"

The call to defineClass:

byte[] fileBytes;
//... read file
Method defineClass;
//... initialize and prepare Method for reflective call
Class clazz = defineClass.invoke("com.foo.sub.Foo", fileBytes, 0, fileBytes.length);

The javadocs state (regarding the name parameter of defineClass): "name - The expected name of the class, or null if not known, using '.' and not '/' as the separator and without a trailing .class suffix."

I don't understand why the exception is being thrown and what the message is supposed to indicate. Any help is appreciated.

Upvotes: 2

Views: 4072

Answers (1)

ruakh
ruakh

Reputation: 183484

According to that method's documentation, it will raise NoClassDefFoundError if you specify a name (in your case com.foo.sub.Foo) that doesn't match the name that the class defines itself as having (inside your fileBytes).

To find out the correct name, try something like

System.out.println(defineClass.invoke(null, fileBytes, 0, fileBytes.length));

(which should print something like class com.foo.sub.Foo).

Upvotes: 3

Related Questions