4

Is it possible to specify a custom classloader for javac (or some alternative java compiler)?

I'd love such a feat because it would allow me to compile classes that use classes that are only found by my special classloader.

For the curious ones: I'd write a classloder that connects to a database and creates classes based on the tables it finds.

Jayan
  • 18,003
  • 15
  • 89
  • 143
Jens Schauder
  • 77,657
  • 34
  • 181
  • 348

6 Answers6

6

When you run javac you can specify the classloader like so:

javac -J-Djava.system.class.loader=org.awesome.classloader sourcefile.java
Hardwareguy
  • 2,941
  • 1
  • 17
  • 13
4

It may be possible to initialize a custom classloader and then use it while calling the new Java 6 Compiler API in javax.tools.

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
1

The only two ways I know of plugging directly into javac (as run on the command line) are via the annotation processor or via a compiler-specific hack.

McDowell
  • 107,573
  • 31
  • 204
  • 267
  • Get a 404 for the compiler-specific hack link, here's the web.archive.org link: http://web.archive.org/web/20140819224858/http://www.iam.unibe.ch/~akuhn/blog/2008/roman-numerals-in-your-java/ – Grant Peters Jan 25 '16 at 00:58
0

Just to expand on Michael's answer, if you cannot use Java6, look at the sun. packages--they have always been available to java apps and have always had a compiler in there, it's just not standard Java so you don't hear about it much and the API is subject to change (like moving it to the javax.tools package!)

Bill K
  • 62,186
  • 18
  • 105
  • 157
0

Take a look at ClassLoader.defineClass. I used it myself for loading plugins into a program I created, in which I loaded a file's bytes into a new class.

Patrick
  • 17,669
  • 6
  • 70
  • 85
0

If the classes all conform to the same Interface you could just provide that at compile time..

If not then I don't see what you are gaining by not outputing .java files based on the DB and compiling that.

Chris Nava
  • 6,614
  • 3
  • 25
  • 31
  • The 'problem' with generation java files and compiling them is it is a separate step. So if someone changes the database the classes don't fit and one gets cryptic sql exceptions. – Jens Schauder Jun 05 '09 at 10:55