重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

字符串解析为java代码 字符串的解析

java字符串怎么转换为代码

方法是有的,但不全实际.

为企业提供成都网站制作、成都做网站、网站优化、网络营销推广、竞价托管、品牌运营等营销获客服务。成都创新互联公司拥有网络营销运营团队,以丰富的互联网营销经验助力企业精准获客,真正落地解决中小企业营销获客难题,做到“让获客更简单”。自创立至今,成功用技术实力解决了企业“网站建设、网络品牌塑造、网络营销”三大难题,同时降低了营销成本,提高了有效客户转化率,获得了众多企业客户的高度认可!

首先,你要理解,JAVA代码的运行是要被编译成字节码codebyte后才能被执行的,以你问题中的意思,那个字符串应该是在怎么代码被编译后项目在运行时,再传入的参数,这时,要想把传入参数的字符串当成JAVA代码来运行,只有一种办法,就是把传进来的字符串转换成字节码,并且,要虚拟加一个方法体出来.这也不是不可行,可用的技术有asm.cglib等字节码技术.但你想,对于你的问题.这样有实际的意义吗

你还不如,把system.out.print重定义成新的外调方法调动来的清晰

java字符串如何解析成能运行的java代码?

java字符串如何解析成运行的java代码

有些情况下,不得不动态运行Java代码,以便提供更加灵活的方式,以下代码可参考(在JDK 1.5+平台上运行通过):

public static void main(String[] args) {

int i = 10;

String code = "System.out.println(\"Hello World!\"+(13+2*5/3));";

code += "for(int i=0;i" + i + ";i++){";

code += " System.out.println(Math.pow(i,2));";

code += "}";

try {

run(code);

} catch (Exception e) {

e.printStackTrace();

}

}

private synchronized static File compile(String code) throws Exception {

File file = File.createTempFile("JavaRuntime", ".java", new File(System.getProperty("user.dir")));

file.deleteOnExit();

// 获得类名

String classname = getBaseFileName(file);

// 将代码输出到文件

PrintWriter out = new PrintWriter(new FileOutputStream(file));

out.println(getClassCode(code, classname));

out.close();

// 编译生成的java文件

String[] cpargs = new String[] { "-d",

System.getProperty("user.dir") + "\\WebRoot\\WEB-INF\\classes",

file.getName() };

int status = Main点抗 pile(cpargs);

if (status != 0) {

throw new Exception("语法错误!");

}

return file;

}

private static synchronized void run(String code) throws Exception {

String classname = getBaseFileName(compile(code));

new File(System.getProperty("user.dir")

+ "\\WebRoot\\WEB-INF\\classes\\" + classname + ".class")

.deleteOnExit();

try {

Class cls = Class.forName(classname);

Method main = cls.getMethod("method", null);

main.invoke(cls, null);

} catch (Exception se) {

se.printStackTrace();

}

}

private static String getClassCode(String code, String className) {

StringBuffer text = new StringBuffer();

text.append("public class " + className + "{\n");

text.append(" public static void method(){\n");

text.append(" " + code + "\n");

text.append(" }\n");

text.append("}");

return text.toString();

}

private static String getBaseFileName(File file) {

String fileName = file.getName();

int index = fileName.indexOf(".");

String result = "";

if (index != -1) {

result = fileName.substring(0, index);

} else {

result = fileName;

}

return result;

}

怎样将字符串转换为可执行的java语句

如,String

aa

=

new

String(

"aa

")

这条语句存储在数据库的表中。

如果你的code变量的内容格式都是这样固定的

可以先解析字符串

得到类、方法和参数的信息

然后可使用反射动态调用该方法

~如果你认可我的回答,请及时点击【采纳为满意回答】按钮

~~手机提问的朋友在客户端右上角评价点【满意】即可。

~你的采纳是我前进的动力

~~O(∩_∩)O,记得好评和采纳,互相帮助,谢谢。


文章题目:字符串解析为java代码 字符串的解析
文章链接:http://cqcxhl.com/article/ddegooo.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP