views:

41

answers:

3

Like

String r = SomeThing.toExecString("new Object().toString()");

And when executed the value of r would be:

"new Object().toString() = java.lang.Object@c5e3974"

Is this even possible at all? Would it need a bunch of reflection? A built in compiler maybe?

+2  A: 
ScriptEngine engine = new ScriptEngineManager().getEngineByName("beanshell");
Object result = engine.eval("new Object().toString();");
System.out.println(result);

You may get close to what you want using BeanShell. I ran the above code with Java 6 with BeanShell 2.0b4 and the JSR 223-based bsh-engine.jar engine on the classpath.

McDowell
Wow, yeap, something like that. And then I can have a method: `toExecString( String v ) { return v + " = + engine.eval( v ); }` powerful ( and dangerous at the same time ;)
OscarRyz
+1  A: 

There is a great post here: Generating Static Proxy Classes - http://www.javaspecialists.eu/archive/Issue180.html

Part one is enough for what you asked, I think

ekeren
A: 

Don't know if you really wanted this. But your problem would be solved with this method:

String toExecString( String code ) {
    return String.format( 
        "\"%s\" = %s@%x", 
        code, 
        code.getClass().getName(), 
        code.hashCode() 
    );
}
tangens
2nd slash should be 1 char to the left.
NomeN
Not really I meant, any expression, for instance `toExecString("1+1")` should yield: `1+1 = 2`
OscarRyz