0

I'm trying to implement a String like a command in Java:

public static void main(String[] args) {
   String command = "System.out.println("hello word");";
   ...
}

I need to convert the command String to a command line, in order to execute output "hello word" in the console. I want to using to this technology to improve code:

SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String month = sdf.format(calIndex.getTime()); 
switch (month) { 
   case "January": 
       leaveDetailCLateLEarly.february += 10;
       break; }
...

The above is quite verbose. I want to write something shorter:

String command = "leaveDetailCLateLEarly."+ month + "+= 10"

Where leaveDetailCLateLEarly is an object and having as an attribute the 12 months. (ie January, February, etc...) Then I have command string: 'leaveDetailCLateLEarly.month= 10' where the month value is able to change (January, February, March, ... ). When project runs, the String will convert to a command line to implement the desired functionality.

Nathaniel Ford
  • 20,545
  • 20
  • 91
  • 102
Duy Nguyen
  • 49
  • 4

2 Answers2

5

Here is a library I wrote many years ago to do this using the Compiler API. Essence JCF It compiles and load any String as a class file. (Including nested classes) without touching the disk.

You can also use Beanshell to dynamically run Java code. This is used by many Java Debuggers, but is not a fully featured version of Java.

Another approach is to use groovy which which supports all the Java code and runs dynamically.

None of these approaches is trivial, or widely used. I suggest you rethink why you need to do this and try a different approach.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

It am not sure really what you are asking. Do you want that if the user inputs the string "command" the "hello world" message is displayed? If so, try this:

Scanner scanner = new Scanner(System.in);
String input ="";
do{
  System.out.println("Command?:");
  input = scanner.nextLine();
while(!input.equals("command"));
System.out.println("Hello world!");
Barbe Rouge
  • 394
  • 1
  • 6
  • 18
  • It may be theoretically possible to write a Java interpreter in Java but it's a huge task and not a worthy goal. Then what happens if you get it to interpret itself? Will the universe implode? – NickJ Aug 28 '13 at 10:22