首页后端开发JAVA字符串解析为java代码 字符串的解析

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

时间2023-04-05 11:58:01发布访客分类JAVA浏览726
导读:java字符串怎么转换为代码 方法是有的,但不全实际.首先,你要理解,JAVA代码的运行是要被编译成字节码codebyte后才能被执行的,以你问题中的意思,那个字符串应该是在怎么代码被编译后项目在运行时,再传入的参数,这时,要想把传入参数的...

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,记得好评和采纳,互相帮助,谢谢。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: 字符串解析为java代码 字符串的解析
本文地址: https://pptw.com/jishu/1730.html
java显示闰年的源代码 java写闰年 java程序代码快捷键 java编程快捷键

游客 回复需填写必要信息