Java - 使用注释和拦截方法?
java中有没有一种简单的方法来拦截方法?我需要向所需的方法添加注释,以便在执行该方法之前调用一段逻辑。
public void verifyActivity() {
// Asset if you are on a wrong page
}
@VerifyActivity
public void testLogin() {
// Login for my automate test
}
@VerifyActivity
public void testSomethingElse() {
// Test some other UI Automation stuff
}
编辑:
推荐的 Android 应用程序 guice 库不包含 AOP。 是否可以使用反射来实现此目的而不添加任何库?
Is there a simple way to intercept methods in java. I need to add an annotation to required methods so that a piece of logic gets called before going through the method.
public void verifyActivity() {
// Asset if you are on a wrong page
}
@VerifyActivity
public void testLogin() {
// Login for my automate test
}
@VerifyActivity
public void testSomethingElse() {
// Test some other UI Automation stuff
}
EDIT:
The recommended guice library for android apps does not contain AOP.
Is it possible to achieve this using reflection without adding any libraries?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Guice 提供了实现注释的简单方法。看看这个。
http://code.google.com/p/google-guice/wiki/AOP
http://code.google.com/p/google-guice/
Guice provides easy way of implementing annotations. Check this out.
http://code.google.com/p/google-guice/wiki/AOP
http://code.google.com/p/google-guice/
正如 sid malani 所说,Google Guice 对此非常有用。一般来说,您想要阅读面向方面的编程教程 ...有一个很好的名为 JMangler 的工具也可能有用
As sid malani said Google Guice is great for this. In general you want to read up on aspect oriented programming tutorials ... There is a nice tool called JMangler that may be of use as well
如果您已通过 动态代理。
You can use reflection if you've coded to interfaces through dynamic proxies.
我怀疑如果没有任何第 3 方库,它是否可以很好地完成。
有一个名为 cglib 的库,它可以做这样的事情。
基本上它会在运行时创建被拦截类的子类。您将能够通过实现 InvocableHandler 来“覆盖”方法,当调用任何超类方法时,它将充当代理。
I doubt that it can be nicely done without any 3rd party libs.
There is a library called cglib, which is capable of such things.
Basically it will create a subclass of the intercepted class at runtime. You'll be able to "override" methods by implementing an InvocationHandler, which will act as a proxy when any of the superclass methods being called.