9

I'm trying to compile and load a class at runtime, without knowing the package of the class. I do know that the class should comply with an interface, and the location of the source, (and hence the class name). I'm trying the following:

/* Compiling source */
File root = new File("scripts");
File sourceFile = new File(root, "Test.java");
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath());

where the Test.java file looks something like

import foo.Itest;
public class Test implements Itest{
...
}

And I get a cannot find symbol symbol : class Itest error from the compiler. How do I provide the compiler with the interface (which has already been loaded) to avoid this error?

[EDIT - RESOLVED]: The error came from the fact the the interface was ITest and the source referred to an Itest interface.

brice
  • 24,329
  • 7
  • 79
  • 95
  • 1
    Motherfriggin typo! The interface loaded is `ITest`, not `Itest`. – brice Aug 10 '10 at 09:33
  • If a Moderator sees this post and feels that it should be deleted, I'm happy with that. – brice Aug 10 '10 at 09:39
  • Possible duplicate of [How do you dynamically compile and load external java classes?](https://stackoverflow.com/questions/21544446/how-do-you-dynamically-compile-and-load-external-java-classes) – ldmtwo Nov 14 '17 at 23:36
  • 1
    Probably related, Mostly the same goal. It's somewhat the the other way round though, by 4 *years*. I'll mark the other as a possible duplicate. – brice Nov 16 '17 at 12:43
  • https://medium.com/@davutgrbz/the-need-history-c91c9d38ec9 – Davut Gürbüz May 10 '20 at 11:28

3 Answers3

3

It seems likely that the compiler.run() is running externally and needs the class path to be set. Have you tried to pass it a suitable class path setting using the last parameter args to the run() call? Perhaps that's why ToolProvider.getSystemToolClassLoader().

This stackoverflow post might also help you.

Community
  • 1
  • 1
Paul Jowett
  • 6,513
  • 2
  • 24
  • 19
1

Not sure if this is what you're looking for but, as mentioned by @Phil here, you could try to pass a classpath argument in your compiler.run method.

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
0

Have you considered generating your class with javassist or something like that?

Maurice Perry
  • 32,610
  • 9
  • 70
  • 97