Java – inject new methods and properties into classes at run time

Is there any way to inject new methods and properties into classes at run time

http://nurkiewicz.blogspot.com/2009/09/injecting-methods-at-runtime-to-java.html Declare that we can do this by using groovy

Can I just use Java?

Solution

The simple answer is to emphasize "you don't want to do that!"

This is technically feasible, but not without the use of extremely complex, expensive and fragile techniques, such as bytecode modification 1 Even so, you must rely on dynamic loading to access modified types and (possibly) reflections to take advantage of their new members In short, you will create a lot of pain for yourself, with little benefit

Java is a statically typed language. Adding / modifying class type signatures may destroy the static types of classes

1 – AspectJ and others allow you to inject other behaviors into classes, but it may not be the "runtime" injection you are pursuing Of course, injected methods cannot be called by statically compiled code

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>