开发者

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

开发者 https://www.devze.com 2022-12-28 21:01 出处:网络
Like String r 开发者_如何学Python= SomeThing.toExecString(\"new Object().toString()\"); And when executed the value of r would be:

Like

String r 开发者_如何学Python= 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?


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.


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


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() 
    );
}
0

精彩评论

暂无评论...
验证码 换一张
取 消