如何使用反射检查方法
public void foo(){
throw new Exception("foo");
}
public void bar(){
foo();
}
是否可以检查方法 bar()
以便知道在 bar 内没有
try catch
的情况下调用了 foo()
()?
public void foo(){
throw new Exception("foo");
}
public void bar(){
foo();
}
Is it possible to inspect the method bar()
in order to know that foo()
is called without a try catch
inside bar()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能有兴趣将整个类包装在代理中,并使用 InvocableHandler 来观察它:
http: //www.javalobby.org/java/forums/t18631.html
我猜,如果您的 IncationHandler 发现“foo”在“bar”之后立即被调用,它会做一些特殊的事情。
You may be interested in wrapping the whole class inside a Proxy and watch it with an InvocationHandler:
http://www.javalobby.org/java/forums/t18631.html
Your InvocationHandler would do something special if it sees that "foo" is called immediatly after "bar", I guess.
看来您的意图是让应用程序代码检查方法实现,并在该方法无法在内部使用
try-catch
时进行条件分支。除非您正在编写单元测试,否则我不鼓励这样做,原因有两个:
如果可以通过检查源代码或API文档来确定方法行为,那么为什么需要在运行时进行验证?
It seems like your intention is to have your application code check a method implementation, and conditional branch when that method fails to use
try-catch
internally.Unless you are writing unit tests, let me discourage doing this for two reasons:
If you can determine method behavior by checking the source code or API documentation, what is the need for verifying at run-time?
据我所知,没有这样的反射 API 允许查看内部实现。您只能检查类中存在的方法,而不能检查方法中编写的逻辑。
As far as my knowledge is concern, there is no such reflection API which allows to see the inside implementations. You can only inspect the methods present in the Class, but can not the logic written in the method.