简体   繁体   中英

How do I compile & instantiate a Java class from source programmatically when it has project dependencies?

This is great , but what if the class in the uncompiled source should inherit from a project specific class (which is already loaded), and has other project dependencies?

As an example, say I want to give users of my software the ability to customize a class at run-time. I have an abstract public class Customizable and a custom class StatusDetails in my project, and lets say the user writes code in a file that looks like this:

import com.somepackage.util.StatusDetails;

public class Test extends Customizable {

    public Test(){
        System.out.println("Initializing Test");
    }

    @Override
    public StatusDetails getStatus(Object params){
        StatusDetails status = new StatusDetails();
        // Populate status based on params
        return status;
    }
}

How could I take that and instantiate it?

First the class will need to be compiled, which means you will have to ship the required JAR files and provide a classpath. To manage this, I highly recommend Apache's Maven, but the learning curve will set you back a bit. The good news is that after your learning curve, you will have a really good tool for building that is fully portable and ideally suited for managing Java projects.

Then you will need to put the output JAR file / classes on the class path of the running program and restart it.

There are other ways of going about it, each with a bit more difficulty. You can avoid the restart by using a classloader, and have the program dynamically load the class in response to a user action.

You can avoid the externalization of the build chain by putting the build chain in the program itself, by calling the compiler tools interface, compiling the program and then using the custom classloader mentioned above to incorporate it into the running program.

The problems with such an approach (as mentioned above) are many. Basically you're giving everyone a huge security hole to exploit. For example, I could "load" code that trashes the filesystem, or opens network sockets for attacking other machines.

I recommend the separate build chain and manual configuration of the load, with a required restart. It may make the user jump through a few more hoops, but it will keep the security holes from being easily exploited.

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