栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何以编程方式编译和实例化Java类?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何以编程方式编译和实例化Java类?

如何加载未编译的Java类?

你需要先编译它。可以使用

javax.toolsAPI
以编程方式完成此操作。这仅需要在JRE顶部的本地计算机上安装JDK。

这是一个基本的启动示例(不包括明显的异常处理):

// Prepare source somehow.String source = "package test; public class Test { static { System.out.println("hello"); } public Test() { System.out.println("world"); } }";// Save source in .java file.File root = new File("/java"); // On Windows running on C:, this is C:java.File sourceFile = new File(root, "test/Test.java");sourceFile.getParentFile().mkdirs();Files.write(sourceFile.toPath(), source.getBytes(StandardCharsets.UTF_8));// 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".

哪个像

helloworldtest.Test@ab853b

如果这些类implements对已经在类路径中的某个接口进行分类,则进一步使用将更加容易。

SomeInterface instance = (SomeInterface) cls.newInstance();

否则,你需要使用Reflection API来访问和调用(未知)方法/字段。

话虽如此,但与实际问题无关:

properties.load(new FileInputStream(new File("ClassName.properties")));

让java.io.File依赖当前的工作目录是可移植性问题的解决方案。不要那样做 将该文件放在类路径中,并

ClassLoader#getResourceAsStream()
与类路径相对路径一起使用。

properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("ClassName.properties"));


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/395088.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号