Inject New Methods and Properties into Classes During Runtime

前端 未结 5 1146
日久生厌
日久生厌 2020-12-06 12:22

Is there any way we can inject new methods and properties into classes during run-time.

http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.h

5条回答
  •  佛祖请我去吃肉
    2020-12-06 13:13

    While it might be possible, it is not useful.

    How would you access these new fields and methods?

    You could not use these methods and fields directly (as "ordinary" fields and methods), since they wouldn't be compiled in.

    If all you want is the possibility to add "properties" and "methods", you can use a Map for the "dynamic properties", and a Map for the "dynamic methods", and look them up by name.

    If you need an extension language for Java, an embedded dynamic language (such as Javascript, or Groovy) can be added; most of these can access arbitrary java objects and methods.

提交回复
热议问题