Extending or adding new classes at runtime in Java

前端 未结 3 1180
情书的邮戳
情书的邮戳 2020-12-11 06:36

Is there a way to add (or extend existing) classes at runtime in java. I\'m stuck on a problem, in which I have to extend an existing class at runtime and add this to the cl

3条回答
  •  天命终不由人
    2020-12-11 07:20

    There are a number of ways you could do this.

    • Compile source code at runtime using the javax.tools package and then load them using a ClassLoader.
    • If you are writing to interfaces, you can decorate classes with a Proxy.
    • Take the more complicated route of bytecode manipulation/generation using a technology like BCEL or ASM (the latter has more up-to-date support for language features, like annotations) and then load the class with a ClassLoader.

    I imagine there are other options.

提交回复
热议问题