Jens Schauder
Jens Schauder

Reputation: 81862

Use a custom classloader at compile time

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.

Upvotes: 4

Views: 1546

Answers (6)

Chris Nava
Chris Nava

Reputation: 6802

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.

Upvotes: 0

Hardwareguy
Hardwareguy

Reputation: 2981

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

javac -J-Djava.system.class.loader=org.awesome.classloader sourcefile.java

Upvotes: 6

Patrick
Patrick

Reputation: 17973

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.

Upvotes: 0

McDowell
McDowell

Reputation: 108859

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.

Upvotes: 1

Bill K
Bill K

Reputation: 62759

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!)

Upvotes: 0

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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

Upvotes: 4

Related Questions