Reflection of method actions in Java

I would like to know how - if even possible - to reflect what method calls are made inside the method at runtime. I'm particularly interested in calling external methods (i.e. Methods in other classes) or calling a specific method, such as getDatabaseConnection ().

My intention was to track the actions of predefined objects inside the methods and execute additional code if some special conditions are fulfilled, since some method is called with certain values. The monitor will be a completely external class or a set of classes that do not have direct access to the object, which will be controlled in no other way than reflection.

+3
source share
3 answers

Aspect J will solve your problem.

Try defining a pointcut as follows:

pointcut profilling(): execution(public * *(..)) && (
            within(com.myPackage..*) ||

This way you will catch the entire invocation of any public method in the com.myPackage package. Add as many sentences inside that you need.

Then add the following code:

Object around(): profilling() {

    //Do wherever you need before method call
    proceed();
    //Do wherever you need after method call

}

IF you want to know more about aspect J, follow this guide .

+2
source

I would expect BCEL to do this. On the website:

The engineering byte code library is designed to provide users with the convenient ability to parse, create, and manipulate (binary) Java class files (those ending in .class).

"" - . JavaDoc - ( ), , , .

+1

BCEL should offer this opportunity, but ...

... your requirements are a lot like Aspect Oriented Programming (AOP), so you probably should also take a look at AspectJ (with the Eclipse tool ).

The main advantage of AspectJ is that it offers a well thought out way to express your specific conditions.

+1
source

Source: https://habr.com/ru/post/1698391/


All Articles