开发者

How to inspect a method using reflection

public void foo(){
    throw new Exception("foo");
}


public void bar(){
    foo();
}
开发者_如何学Go

Is it possible to inspect the method bar() in order to know that foo() is called without a try catch inside 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.


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:

1. A developer should understand his application logic.

You should already know what your code is doing. If the method is part of a closed-source API, check the documentation for thrown Exception types.

2. It adds unnecessary complexity.

Because flow of execution depends on method implementation, you will have an application whose behavior is dependent upon the state of its own source. (eg. Changing the method can create side-effects, which makes debugging more difficult.)

If you can determine method behavior by checking the source code or API documentation, what is the need for verifying at run-time?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜