5

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!

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks. this is a considerable approach! but generating source code is also hard for me.
@CaiNiaoCoder, can you explain in detail from what input you want to generate source code of class?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.