简体   繁体   中英

How can I execute a method of a class that has been uploaded?

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:

  1. Create your own classloader (not hard, see below).
  2. Load the class using ClassLoader#defineClass(String, byte[], int, int) .
  3. Check it implements your interface ( YourInterface.class.isAssignableFrom(loadedClass); ).
  4. Use java reflection/introspection on the Class<?> you just got on step 1. (eg YourInterface obj = (YourInterface)loadedClass.newInstance(); ).
  5. Call the method: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM