开发者

Creating new classes from code

Is there a way to create a new java 开发者_JAVA技巧class during execution? All the information about the class (name, modifiers, methods, fields, etc.) exists. Now I want to create that class. An idea was to create a new file and write the stuff to that file, c'est fini! But I think there are more elegant ways to do that, maybe with JDT?


Either use BCEL to create byte code and class files (the hard way) or create the source code in memory and use the Java 6 Compiler API (that's what I would do). But with Compiler API you need a Java SDK while running the application, a JRE is not sufficient.

Further Reading

  • The Java 6.0 Compiler API

(There a lot of tutorials on the web)


If you are writing an eclipse plugin and you want your tooling to generate code into a project, you can interact with JDT using the AST. There is also a method to call the Eclipse batch compiler from your runtime.

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 :-) but you have access to the JDT java core model as you go.

If you need to generate files into your eclipse workspace, there are also template based options, like JET.

But if you want to dynamically generate and load a .class file in the runtime of a java application try @Andreas_D suggestions.


Look at code generation libraries, http://cglib.sourceforge.net/ http://www.csg.is.titech.ac.jp/~chiba/javassist/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜