java开发 类实例化,如何以编程方式编译和实例化Java类?

How do I load a Java Class that is not compiled?

你需要先编译它.这可以通过javax.tools API以编程方式完成.这只需要将JDK安装在JRE顶部的本地计算机上.

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

// 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@hashcode".

产量如何

hello

world

test.Test@ab853b

如果这些类实现了已经在类路径中的某个接口,那么进一步使用会更容易.

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"));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值