vipincd
vipincd

Reputation:

Executing java code given in a text file

I have a set of java code in a text file. Is it possible for me to read line by line from the text file and execute the commands as in eval function of javascript? Thanks in advance

Upvotes: 4

Views: 6042

Answers (5)

HeDinges
HeDinges

Reputation: 4607

Maybe it would be easier to start looking for scripting languages, which are very well supported by the Java VM.

Groovy is first to come in mind, it has a Java like syntax.

Upvotes: 3

soulmerge
soulmerge

Reputation: 75704

Possibly. It can be done non-trivially using the compiler API. But you're really better off writing an XML configuration that controls your program, rather than allow executing arbitrary code in a text file.

Upvotes: 1

Markus Lausberg
Markus Lausberg

Reputation: 12257

You can use Janino to compile your generated *.java file. After you compiled your file, you can load the *.class file and call a method by reflection.

Upvotes: 0

Boris Pavlović
Boris Pavlović

Reputation: 64632

Try using BeanShell. From the introductory page:

What is BeanShell?

BeanShell is a small, free, embeddable Java source interpreter with object scripting language features, written in Java. BeanShell dynamically executes standard Java syntax and extends it with common scripting conveniences such as loose types, commands, and method closures like those in Perl and JavaScript.

You can use BeanShell interactively for Java experimentation and debugging as well as to extend your applications in new ways. Scripting Java lends itself to a wide variety of applications including rapid prototyping, user scripting extension, rules engines, configuration, testing, dynamic deployment, embedded systems, and even Java education.

BeanShell is small and embeddable, so you can call BeanShell from your Java applications to execute Java code dynamically at run-time or to provide extensibility in your applications. Alternatively, you can use standalone BeanShell scripts to manipulate Java applications; working with Java objects and APIs dynamically. Since BeanShell is written in Java and runs in the same VM as your application, you can freely pass references to "live" objects into scripts and return them as results.

In short, BeanShell is dynamically interpreted Java, plus a scripting language and flexible environment all rolled into one clean package.

Upvotes: 8

David Johnstone
David Johnstone

Reputation: 24450

No. Java is a compiled language, so this behaviour is impossible unless you invoke the compiler first. (And there is no guarantee that a machine with Java has the Java compiler.)

Upvotes: 3

Related Questions