开发者

Adding new functionality to an application using on-the-fly class generation

Is it possible to generate subclasses at runtime or while an application is running? If so, how is this achieved and what precautions should be taken to prevent a rogue object wreaking havoc inside an application?

开发者_C百科

Edit: Title modified from "Class generation on the fly".


Take a look at Reflection API.

Create Dynamic class "on the fly"

Read this one too:

Java Reflection: Create an implementing class - Jon Skeet answered it! :)


Yes. Have a look at what you can do with the compiler in Javassist.


Yes, it is possible

Take a look at the package "javax.tools"

You could compile and load a class at runtime.

    String rogue = "package abc; "+
                 "public class RogueObjectWreakingHavoc extends SomeImportantClass {"+
                 " { System.exit(-1) }"+
                 "}"
    File sourceFile = new File("RogueObjectWreakingHavoc.java");
    FileWriter fileWriter = new FileWriter(sourceFile);
    fileWriter.write(rogue);
    fileWriter.close();

    List<File> files = new ArrayList<File>();
    files.add(sourceFile);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null,
                                                                          null,
                                                                          null);

    compiler.getTask(null, 
                     fileManager,
                     null,
                     null,
                     null,
                     fileManager.getJavaFileObjectsFromFiles(files))
    .call();
    fileManager.close();

   // load using URLClassLoader...

To avoid it you most consider declare your classes as final if they are not indented to be subclasses, and make copies when needed ( instead of taking arguments just they way they are )

More information ( about how to use Java effectively ) on the book "Effective Java" by Joshua Bloch


For other developpers seeking to add the possibility of extending their software, another approach for plugin behaviour is the forName() method of Class (used for example by JDBC) and Dynamic Class Loading.

http://mindprod.com/jgloss/classforname.html

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜