Create a string with the result of the expression and the expression that triggered the value. Is it possible?

how

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

      

And when executed, the value r

will be:

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

      

Is this even possible? Do they need a lot of thought? An embedded compiler perhaps?

+2


a source to share


3 answers


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

      



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

+2


a source


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



Part one is enough for what you asked, I guess

+1


a source


I don't know if you really wanted this. But your problem will be solved with this method:

String toExecString( String code ) {
    return String.format( 
        "\"%s\" = %s@%x", 
        code, 
        code.getClass().getName(), 
        code.hashCode() 
    );
}

      

0


a source







All Articles