Вопрос

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()?

Это было полезно?

Решение

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top