如何使字符串进入代码 [英] How to make a string in to code

查看:164
本文介绍了如何使字符串进入代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

将字符串转换为代码

运行字符串中包含的代码片段

有什么办法把变量(string)变成一段代码?
我的字符串必须是可变的(非静态的)
如果你可以简单地解释一下就好:D

is there any way to turn a variable(string) into to a piece of code? My string has to be changeable (non-static) If you can explain it simply that would be nice :D

推荐答案

我假设你想用一些Java语句创建一个 String 对象,并且像内容一样执行。

I assume, that you want to create a String object with some Java statements and execute the content as if it was a method.

不,这是不可能的,因为这意味着,java是一种解释型编程语言。不是这样的。

No, it is not possible, because that would imply, that java was an interpreted programming language. Which is not the case.

您可以将行与某种类模板(在另一个字符串)合并,将其存储到文件中,使用jdk(使用`Runtime调用javac)进行编译。 exec)并使用自定义类加载器加载类,然后反映方法并希望最好。

You could merge the line with some sort of class template (on another string), store it to a file, compile that using the jdk (call javac with `Runtime.exec) and load the class with a custom classloader, then reflect the method and hope for the best.

使用相当新的Java Compiler API有一个相当复杂的方法,但我猜,这远远超出你的需要。 (还有一些更复杂的技巧,因为eclipse IDE提供了允许执行Java语句的视图。)

There is a rather complicated way using the fairly new Java Compiler API, but I guess, that is far beyond your needs. (And there have to be some more complicated tricks, because the eclipse IDE provides views that allow executing Java statements.)

这篇关于如何使字符串进入代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆