jeudi 9 avril 2015

Java: How to listen on methods invocation without registering each object explicitely?

I want to listen on method calls in order to attach additional behavior dynamically around the call. I've already done it on JUnit methods with a custom annotation and runner. I'm trying to do it on a standard java application.


The main idea is to do:



@Override
public void beforeInvoke (Object self, Method m, Object[] args){
Object[] newargs = modifyArgs (args);
m.invoke (self, newargs);
}


It's just an abstract idea, I don't have any concrete example, but I'm curious if it's possible in java.


I've found some approaches:



java.lang.reflect.Proxy.newProxyInstance(...)


where a proxy is defined for an interface only (but not used to decorate concrete classes). It seems similar to injection pattern and it's a different concern.


Another approach here using a factory pattern with the ProxyFactory class. This other solution requires explicit calls to create() method to produce object proxies listening on method invocations. So, if you bypass it by using natural constructors of your classes, it's not working. It's very constraining if you must explicit a call to a factory each time you have to create an object.


There is a way to do it with transparency ? Like Proxy.newProxyInstance() but working also on concrete classes ?


Thanks.






Aucun commentaire:

Enregistrer un commentaire