如何在Java中拦截对象创建 [英] How to intercept object creation in Java

查看:205
本文介绍了如何在Java中拦截对象创建的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一点奇怪的要求。我猜。

I have a little weird requirement.I guess.

我想使用我创建的自定义代理来装饰实现特定接口的所有对象,但是我需要这对代码本身透明。可以包含在构建过​​程中的东西将是完美的。

I'd like to use a custom Proxy I created to decorate all object that implements an specific interface, but I need this to be transparent to the code itself. Something that could be included in the build process would be perfect.

我在AOP中思考但没有看到这样的功能,我正在寻找想法,甚至是疯狂的。我正在考虑在编译之后更改源代码并重新编译它至少替换对new的直接调用(我想这不会通过反射创建对象但是会是一个很好的开始)但我可以想到一百万个问题这可能会带来,打破我的主要目标,即使这种仪器尽可能透明。

I was thinking in AOP but didn't see such capabilities, I'm looking for ideas, even the crazy ones. I'm thinking on changing the source code after compilation and recompiling it replacing at least the direct calls to new(I guess this would not get object creation by reflection but would be a nice start) but I can think of a million of problems that this could bring, breaking my main objective that is make such instrumentation as transparent as possible.

你们有些人对这种不同寻常的事情有过一些经验吗?

Did some of you have some experience on such unusual thing ?

问候

推荐答案

使用注释来装饰类并使用注释处理来注入您需要的代码。

Use an annotation to decorate the classes and use annotation processing to inject the code you need.

fyi, Hibernate 使用此代码方法

fyi, Hibernate employs this approach

这篇关于如何在Java中拦截对象创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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