How to convert a string into a piece of code (Factory Method Pattern?)

≯℡__Kan透↙ 提交于 2019-12-24 09:29:38

问题


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";

回答1:


GroovyShell is the answer:

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

def result = new GroovyShell().evaluate string2code
assert result == "HELLO"



回答2:


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 ){
        ...
    }
}



回答3:


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.



来源:https://stackoverflow.com/questions/17478967/how-to-convert-a-string-into-a-piece-of-code-factory-method-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!