Amit_dash_234
Amit_dash_234

Reputation: 101

Lightweight scripting support in Java

I was wondering if it's possible to have some sort of scripting in Java that can hook text files stored outside and have them imported into the application as a class object.

Some context : I'm developing a scientific calculator that supports custom functions and operations, while this functionality is available to programmers as they can easily just implement the necessary interface and deal with it. however I recently received the request to add a new feature where the general users should be able to write their own custom functions/operations or both and the app should be able to interpret them and have them imported into its list of functions.

I was initially planning on allowing the users to just be able to write a plain text file and store it in a specific folder, and the app will be able to load this text files as an input stream, I was going for a string token parsing sort of approach but I have no idea how will I make this work or how will I go about converting them into objects(implenting those necessary interfaces), if anyone can hint me on how such a thing would be accomplished or if it's even possible.

And no code to show for now.

Upvotes: 0

Views: 60

Answers (1)

Pam Stums
Pam Stums

Reputation: 176

The best match for this requirement I know is Java's Reflection.

Your calculator should define an interface that anyone can implement. The implementation class can be later placed in your calculator classpath so it can detect it at runtime and instantiate it using reflection.

As the implementation classes all implements the known interface, you can cast the instance to that interface and execute the known method.

This way you get to run external code, unknown to the calculator which can be added dynamically.

So the steps are:

  1. Define an interface e.g:

    public interface CalculatorExecutable { void runMe(); }

  2. Others can write classes that implement this interface.

    public class MyOp implements CalculatorExecutable { public void runMe() { /* any implementation here */ } }

  3. As you mentioned, you can read all the class names from a directory you designate, simply read all the files in that directory and filter for only those files with .class extension

  4. After you instantiate with Class.forName( classNameGoesHere ); you can cast to your interface and execute your "runMe" method.

Upvotes: 1

Related Questions