【问题标题】:To generate Java Class on Fly and add to class path即时生成 Java 类并添加到类路径
【发布时间】:2019-10-10 15:13:12
【问题描述】:

我正在动态生成一个 java 类并尝试在其上调用一个方法。为此,似乎我必须执行以下操作

  • 编译类(javac 文件名不起作用,因为它依赖于其他依赖项)
  • 在运行时将类添加到类路径中

我怎样才能做到这一点?

【问题讨论】:

标签: java java-8


【解决方案1】:

我让它与 JavaCompiler 和自定义类加载器一起工作,如下所示。

 private Path compileSource(Path javaFile, String contractFileNameWithoutExtension) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        compiler.run(null, null, null, javaFile.toFile().getAbsolutePath());
        return javaFile.getParent().resolve(contractFileNameWithoutExtension+".class");
    }


public Class findClass(String name) {
        String filePath = sourceCodeLocation +"/"+ name.replace(".", "/")+".class";
        byte[] b = loadClassFromFile(filePath);
        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassFromFile(String fileName)  {
        try {
            InputStream inputStream = FileUtils.getFileInputStream.apply(fileName);
            byte[] buffer;
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int nextValue = 0;
            try {
                while ((nextValue = inputStream.read()) != -1) {
                    byteStream.write(nextValue);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            buffer = byteStream.toByteArray();
            return buffer;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

【讨论】:

    猜你喜欢
    • 2012-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    相关资源
    最近更新 更多