Creating new classes from code

Is there a way to create a new java class at runtime? All class information (name, modifiers, methods, fields, etc.) exists. Now I want to create this class. The idea was to create a new file and write material to this file, c'est fini! But I think there are more elegant ways to do this, maybe with JDT?

+3
source share
3 answers

Either use BCELto create byte code and class files (the hard way), or create the source code in memory and use the Java 6 compiler API (which I will do). But with the help of the compiler API you need the Java SDK at application launch time, the JRE is not enough.

additional literature

( )

+4

eclipse , , JDT, AST. Eclipse .

AST ast = AST.newAST(AST.JLS3);
CompilationUnit unit = ast.newCompilationUnit();
PackageDeclaration packageDeclaration = ast.newPackageDeclaration();
packageDeclaration.setName(ast.newSimpleName("example"));
unit.setPackage(packageDeclaration);
ImportDeclaration importDeclaration = ast.newImportDeclaration();
QualifiedName name = 
    ast.newQualifiedName(
    ast.newSimpleName("java"),
    ast.newSimpleName("util"));
importDeclaration.setName(name);
importDeclaration.setOnDemand(true);
unit.imports().add(importDeclaration);
TypeDeclaration type = ast.newTypeDeclaration();
type.setInterface(false);
type.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.PUBLIC_KEYWORD));
    type.setName(ast.newSimpleName("HelloWorld"));
// ....

Long winded:-), JDT java, .

eclipse, , JET.

.class Java-, @Andreas_D .

+3

, http://cglib.sourceforge.net/ http://www.csg.is.titech.ac.jp/~chiba/javassist/

+1

All Articles