Benifir
Benifir

Reputation: 24

In Application Compiling - Java

I'm writing an application where there is a text editor for the user to write his or her own code. I then want to compile said code, which is easy enough. The trick I don't know how to do is call a function in the applications source from the users compiled code

For example, if I have a class titled 'Player' with a function MoveUp (); , how could I call that function from the users compiled code?

Upvotes: 1

Views: 62

Answers (1)

Michael Sharp
Michael Sharp

Reputation: 496

If you know how to compile the code already, and you know where the compiled class file is stored its actually not too bad. It just requires a bit of reflection.

    //replace filePath with the path to the folder where the class file is stored
    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[]{filePath.toURI().toURL()});

    //this actually loads the class into java so you can use it
    Class<?> cs = Class.forName(compiledClassName, true, classLoader);

    //the getConstructor method will return the constructor based on the 
    //parameters that you pass in. The default constructor has none, but if 
    //you want a different constructor you just pass in the class of the 
    //object you want to use
    Constructor<?> ctor = cs.getConstructor();

    //you can then just create a new instance of your class
    Player player = (Player) ctor.newInstance();

    //You can then call any methods on the Player object that you want.
    player.MoveUp();

Remember that when you are compiling the code that the class package can move the location of the compiled class files. It may be easier to just remove the package statement of their code, or add package where you want it to go.

As a side note, if you are going to be doing this to multiple "Player" classes at the same time, each class will need a unique name for it. If they don't have that, they will end up sharing the same class file and all having the same code because of that.

Upvotes: 1

Related Questions