如何从Web App项目执行和包含Java API

如何从Web App项目执行和包含Java API,第1张

如何从Web App项目执行和包含Java API

请在 如何以编程方式编译和实例化Java类上查看BalusC的解决方案?为了进行测试,请复制并粘贴以下JSP。我希望BalusC不介意我更改了他的代码。

<%@ page import="java.util.*,java.io.*,javax.tools.*,java.net.*" %><%System.setOut(new PrintStream(response.getOutputStream()));// Prepare source somehow. String source = "package test; public class Test { static { System.out.println("hello"); } public Test() { System.out.println("rickz"); } }";  // Save source in .java file. File root = new File("/testJava"); // On Windows running on C:, this is C:testJava. File sourceFile = new File(root, "test/Test.java"); sourceFile.getParentFile().mkdirs(); new FileWriter(sourceFile).append(source).close();  // Compile source file. JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); compiler.run(null, null, null, sourceFile.getPath());  // Load and instantiate compiled class. URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); Class<?> cls = Class.forName("test.Test", true, classLoader); // Should print "hello". Object instance = cls.newInstance(); // Should print "world". System.out.println(instance); // Should print "test.Test@hashpre". if(out != null) return;%>


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5641801.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存