0

I am generating a java class on fly and trying to invoke a method on it. For this, seems like I have to do the following

  • Compile the class (javac filename will not work as it depends on may other dependencies)
  • Add the class to the class path at runtime

How can I achieve this?

Naman
  • 27,789
  • 26
  • 218
  • 353
Minisha
  • 2,117
  • 2
  • 25
  • 56
  • 1
    maybe the [JavaCompiler](https://docs.oracle.com/javase/8/docs/api/javax/tools/JavaCompiler.html) interface is what you require? – Abra May 24 '19 at 04:22
  • 1
    Possibly something already answered https://stackoverflow.com/questions/1011443/extending-or-adding-new-classes-at-runtime-in-java ? – Naman May 24 '19 at 05:40
  • Possible duplicate of [Creating classes dynamically with Java](https://stackoverflow.com/questions/2320404/creating-classes-dynamically-with-java) – AshwinK May 24 '19 at 18:38
  • The existing question doesn't have compilation and class loader idea combined, I guess. Anyways, @Abra answer helped me to come up with the solution. Thanks – Minisha May 24 '19 at 23:53

1 Answers1

2

I made it work with JavaCompiler and Custom class loader like below.

 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);
        }
    }
Minisha
  • 2,117
  • 2
  • 25
  • 56