Inject New Methods and Properties into Classes During Runtime

前端 未结 5 1121
日久生厌
日久生厌 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:07

    Is it possible by just doing using Java?

    The simple answer is an emphatic "You don't want to do that!".

    It is technically possible, but not without resorting to extremely complex, expensive and fragile tricks like bytecode modification1. And even then, you have to rely on dynamic loading to access the modified type and (probably) reflection to make use of its new members. In short, you would be creating lots of pain for yourself, for little if any gain.

    Java is a statically typed language, and adding / modifying class type signatures can break the static typing contract of a class.


    1 - AspectJ and the like allow you to inject additional behaviour into a class, but it is probably not the "runtime" injection that you are after. Certainly, the injected methods won't be available for statically compiled code to call.

提交回复
热议问题