1

Let's say we have a String like this:

String string2code = "variable = 'hello';";

How could we convert that String to a piece of code like this?:

variable = "hello";
chelder
  • 3,819
  • 6
  • 56
  • 90
  • 3
    check this question [Run Piece of Code contained in a String](http://stackoverflow.com/questions/4389232/run-piece-of-code-contained-in-a-string) – Ibrahim Najjar Jul 04 '13 at 22:53
  • Thank you for the link with the solution for Java. I'm using Grails so I can use Java or Groovy. The Groovy solution is easier than the one provided by Java so I marked it as the answer. – chelder Jul 05 '13 at 14:41
  • no problem, you are welcom. – Ibrahim Najjar Jul 05 '13 at 18:06

3 Answers3

1

GroovyShell is the answer:

String string2code = "variable = 'hello'; return variable.toUpperCase()";

def result = new GroovyShell().evaluate string2code
assert result == "HELLO"
Will
  • 14,348
  • 1
  • 42
  • 44
  • Thank you. Unfortunately, it does not work with the querying system of Grails. I posted the new question here: http://stackoverflow.com/questions/17491301/is-possible-to-convert-a-string-into-a-piece-of-code-in-grails-if-it-includes-a – chelder Jul 05 '13 at 14:34
1

If you're into more complex stuff later, you can compile whole classes using GroovyClassLoader.

private static Class loadGroovyClass( File file ) throws MigrationException {
    try {
        GroovyClassLoader gcl = new GroovyClassLoader( ExternalMigratorsLoader.class.getClassLoader() );

        GroovyCodeSource src = new GroovyCodeSource( file );
        Class clazz = gcl.parseClass( src );
        return clazz;
    }
    catch( CompilationFailedException | IOException ex ){
        ...
    }
}
Ondra Žižka
  • 43,948
  • 41
  • 217
  • 277
0

Maybe you can take a look a Janino

Janino is a small java compiler than not only can compile source files, it can compile expressions like the one you have.

futuretelematics
  • 1,453
  • 11
  • 23
  • Thank you. If I am not wrong, it would be one more solution for Java. @Sniffer wrote the next link with more possibilites for Java: http://stackoverflow.com/questions/4389232/run-piece-of-code-contained-in-a-string – chelder Jul 05 '13 at 14:37