Create arbitrary Java class at runtime
Does anyone know of a开发者_如何学JAVAny Java libraries that would allow me to define a new Java class at runtime and also instantiate an instance of that class?
ASM is an all purpose Java bytecode manipulation and analysis framework. It can be used to modify existing classes or dynamically generate classes, directly in binary form.
I'm not sure whether this is what you're looking for but consider Javassist or cglib library.
Javassist (Java Programming Assistant) makes Java bytecode manipulation simple. It is a class library for editing bytecodes in Java; it enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. [...]
cglib is a powerful, high performance and quality Code Generation Library, It is used to extend JAVA classes and implements interfaces at runtime. [...]
If you don't want to work at bytecode level, a possible solution is to use the Compiler API of Java SE 6. See here for an example.
Java's Proxy class can be used to create dynamic classes that implement specific interfaces at runtime. Such classes use an InvocationHandler to handle method calls.
精彩评论