JohnJohnGa
JohnJohnGa

Reputation: 15685

How to inspect a method using reflection

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

Upvotes: 3

Views: 1321

Answers (3)

Rob
Rob

Reputation: 5286

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?

Upvotes: 2

Vicente Plata
Vicente Plata

Reputation: 3380

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.

Upvotes: 6

Naved
Naved

Reputation: 4118

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.

Upvotes: 0

Related Questions