Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject New Methods and Properties into Classes During Runtime

Tags:

java

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.html states we may do that by using Groovy.

Is it possible by just doing using Java?

like image 310
Cheok Yan Cheng Avatar asked Sep 14 '09 05:09

Cheok Yan Cheng


4 Answers

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.

like image 161
Stephen C Avatar answered Nov 08 '22 03:11

Stephen C


So if you were really crazy, you could do something like what they outline here. What you could do is load the .java file, find the correct insertion point, add whatever methods you need to, call the java compiler and reload the class. Good luck debugging that mess though :)

Edit This actually might be of some use...

like image 44
Chris Thompson Avatar answered Nov 08 '22 02:11

Chris Thompson


You can do some quite funky things with AOP, although genuine modification of classes at runtime is a pretty hairy technique that needs a lot of classloading magic and sleight of hand.

What is easier is using AOP techniques to generate a subclass of your target class and to introduce new methods into this instead, what AOP called a "mixin" or "introduction". See here to read how Spring AOP does it, although this may be quite lame compared to what you're actually trying to achieve.

like image 1
skaffman Avatar answered Nov 08 '22 01:11

skaffman


Is it possible by just doing using Java?

Quite so, the "only" thing you have to do is define an instrumentation agent which supplies an appropriate ClassFileTransformer, and you'll have to use reflection to invoke the added methods. Odds are this isn't what you want to do, though, but it's doable and there's a well-defined interface for it. If you want to modify existing methods you may be interested in something like AspectJ.

like image 1
gustafc Avatar answered Nov 08 '22 02:11

gustafc