Java:如何在不明确注册每个对象的情况下侦听方法调用?

编程入门 行业动态 更新时间:2024-10-11 11:18:56
本文介绍了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:如何在不明确注册每个对象的情况下侦听方法调用?

本文发布于:2023-11-26 04:28:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632626.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:不明确   情况下   对象   方法   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!