Java:如何在不明确注册每个对象的情况下侦听方法调用? [英] Java: How to listen on methods invocation without registering each object explicitely?

查看:64
本文介绍了Java:如何在不明确注册每个对象的情况下侦听方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想监听方法调用,以便在调用周围动态附加其他行为.我已经使用自定义注释和运行器在 JUnit 方法上完成了它.我正在尝试在标准 Java 应用程序上执行此操作.

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.

主要思路是:

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

这只是一个抽象的想法,我没有任何具体的例子,但我很好奇在java中是否可行.

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

我找到了一些方法:

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.

另一种方法此处 使用带有 ProxyFactory 类的工厂模式.另一种解决方案需要显式调用 create() 方法以生成侦听方法调用的对象代理.因此,如果您通过使用类的自然构造函数绕过它,它将无法正常工作.如果每次必须创建对象时都必须显式调用工厂,这是非常受限制的.

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.

有没有办法做到透明?像 Proxy.newProxyInstance() 但也在具体类上工作?

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

谢谢.

推荐答案

嗯,这在 Spring 框架和面向切面编程中很常见.由于您将构造函数调用委托给 Spring,因此 Spring 很容易设置代理来拦截对实际对象的调用.

Well,this is commonly seen with Spring Framework and Aspect Oriented Programming. Since you delegate your constructor calls to Spring, it is quite easy for Spring to put a proxy in place to intercept calls to the actual objects.

据我所知,拦截调用的唯一方法是使用代理.无论是您提到的方式,还是使用 Spring 和 AOP.

As far as I can tell, the only way to intercept calls is to use a proxy. Either in the way you mentioned or using Spring and AOP.

这篇关于Java:如何在不明确注册每个对象的情况下侦听方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆