Michael Liddle
Michael Liddle

Reputation: 21

Is it possible to define a Java ClassLoader that returns completely different classes to the one's requested?

I've tried this, but get a ClassNotFoundException when calling:

Class.forName("com.AClass", false, mySpecialLoader)

Upvotes: 2

Views: 581

Answers (2)

Jevgeni Kabanov
Jevgeni Kabanov

Reputation: 2642

It is impossible to return a class named differently than the one requested. However it is possible to use bytecode manipulation tools like ASM to automatically rename the class you want to return to the one requested.

Upvotes: 1

Brian Deterling
Brian Deterling

Reputation: 13724

The ClassLoader will have to call defineClass to get the Class. According to the JavaDoc for defineClass:

If name is not null, it must be equal to the binary name of the class specified by the byte array.

If the name is null, it will get it from the bytecode. So you can return any class you want as long as it's called com.AClass. In other words, you could have multiple versions of com.AClass. You could even use something like JavaAssist to create a class on the fly.

But that doesn't explain the ClassNotFoundException - it sounds like your class loader isn't returning anything.

Upvotes: 5

Related Questions