在飞行上生成Java类并添加到类路径



我正在飞行生成一个Java类,并试图在其上调用一种方法。为此,我似乎必须做以下

  • 编译类(Javac FileName将不起作用,因为这取决于其他依赖项(
  • 在运行时将类添加到类路径

我该如何实现?

我使其与下面的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);
        }
    }

最新更新