outrage
outrage

Reputation: 25

Load a class which implements another one - Java

I'm trying to load some classes dynamically by getting their bytes and using reflection to use the defineClass method. Here is my code (this is a loop)

Method m = java.lang.ClassLoader.class.getDeclaredMethod("defineClass", String.class, byte[].class, int.class, int.class);
            m.setAccessible(true);
            m.invoke(Main.class.getClassLoader(), className, classBytes, 0, classBytes.length);

But when a class implements another one, it throws a NoClassDefFoundError (the implemented class isn't load yet). I don't know how to do, I tried to load few times to resolve this but it doesn't work. I also searched to add all classes to the classpath before loading them but I don't know how to do this with an array of byte.

Upvotes: 0

Views: 86

Answers (1)

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

Dynamic class loader is what Java does. There shouldn't be a need to bypass language access restrictions. Subclass SecureClassLoader in the usual way.

Upvotes: 1

Related Questions