Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java generate class file at runtime

Tags:

java

I need to generate class at runtime, each class is mapped to a database table. Such class is model class used in ORM.

When client specify a database table to work with, my application check for existence of corresponding model class , if it does not exist, generate it and load it for use and save it, so next time we don't need to generate this class again

my question is:

  1. Is that possible?
  2. What open source library to use for generating class at runtime ?

some example code that illustrating how to generate simple POJO class is welcome!

best regards!

like image 260
CaiNiaoCoder Avatar asked Sep 30 '11 09:09

CaiNiaoCoder


People also ask

Can we create a class at runtime in Java?

Dynamic Class creation enables you to create a Java class on the fly at runtime, from source code created from a string. Dynamic class creation can be used in extremely low latency applications to improve performance.

How do I create a .class file in Java?

To create a new Java class or type, follow these steps: In the Project window, right-click a Java file or folder, and select New > Java Class. Alternatively, select a Java file or folder in the Project window, or click in a Java file in the Code Editor. Then select File > New > Java Class.

How do I create a .class file in eclipse?

File > New > Class It is the wizard to create new Java class in Eclipse.

How many class files will be generated on compiling this file?

For Compiling: After compilation there will be 3 class files in corresponding folder named as: Sample. class.


1 Answers

Yes, this is possible. And you don't need an external lib. The JDK provides everything you need:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
int compilationResult = compiler.run(null, null, null, fileToCompile);
if (compilationResult == 0) {
    System.out.println("Compilation is successful");
} else {
    System.out.println("Compilation Failed");
}

Check out the JavaCompiler docs.

like image 128
nfechner Avatar answered Oct 04 '22 17:10

nfechner