The goal is to implement a web application that can execute methods of .class
files that has been uploaded. The uploaded class file is available as a byte[]
. The public class in this .class
file implements a specific interface.
After the upload, I'd like to call a method (interface implementation).
Is there a way to do so in a running java application? If yes, how?
Btw. I'm aware of the security risks.
Shouldn't be too hard:
ClassLoader#defineClass(String, byte[], int, int)
. YourInterface.class.isAssignableFrom(loadedClass);
). Class<?>
you just got on step 1. (eg YourInterface obj = (YourInterface)loadedClass.newInstance();
). obj.shinyMethod();
Re creating your own classloader: Here's a simple one that just delegates to the system class loader:
class MyClassLoader extends ClassLoader {
public MyClassLoader() {
super(ClassLoader.getSystemClassLoader());
}
// Our custom public function for loading from a byte array,
// this is here just because defineClass is final, so we
// can't just make it public. Name can be anything you want.
public Class<?> loadClassFromByteArray(byte[] data)
throws ClassFormatError {
return this.defineClass(null, data, 0, data.length);
}
}
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.