Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a class while a Java application is running

In Java, is it possible to create a class definition on the fly while an application is running, and then create an object of that class?

For example, a running application would read in a text file that contains a list of class members to include in the new class. The application would then define a class definition based on the list of members, and then insantiate it.

like image 746
Lehane Avatar asked Apr 23 '09 13:04

Lehane


People also ask

How do you define a class in Java?

Defining a Class in Java In general, class declaration includes the following in the order as it appears: Modifiers: A class can be public or has default access. class keyword: The class keyword is used to create a class. Class name: The name must begin with an initial letter (capitalized by convention).

Can you define a class in a method Java?

You can define a local class inside any block (see Expressions, Statements, and Blocks for more information). For example, you can define a local class in a method body, a for loop, or an if clause.


3 Answers

Yes its possible to do so in theory your class file is byte code which is at the end a byte array! you can then use the method defineClass(String, byte[], int, int) to get a Class instance that can be used to instantiate objects via reflection.

In practice you can use something like CGLib or javaassist.

You can also use the long way of generating the java code in a file, invoking the compiler, then loading the file.

like image 116
MahdeTo Avatar answered Nov 14 '22 04:11

MahdeTo


You can dynamically generate classes using ASM

like image 41
Boune Avatar answered Nov 14 '22 04:11

Boune


You can do this by writing the code for your new class out to a file, then invoking the Java compiler on that file and using a classloader to dynamically load that class into your running application. Apache Tomcat does this for its JSP pages; it takes the code, makes some changes to it, wraps it in a try/catch block in the middle of a class, which it then writes to the filesystem, compiles it, and uses a classloader to get and sue it to serve requests.

like image 35
Eli Courtwright Avatar answered Nov 14 '22 04:11

Eli Courtwright