Finding a Simple Recipe for Java Annotation

I have never written annotations in Java.

I have a simple Java class for measuring performance. I call it PerfLog. Here is an example of its use:

public class MyClassToTest {
  public String MyMethod() {
    PerfLog p = new PerfLog("MyClassToTest", "MyMethod");
    try {
       // All the code that I want to time.
       return whatever;
    } finally {
       p.stop();
    }
  }
}

When p.stop () is called, the line is written to the log file:

2010/10/29T14:30:00.00 MyClassToTest MyMethod elapsed time: 00:00:00.0105

Is it possible to rewrite PerfLog as an annotation so that I can write this instead?

public class MyClassToTest {
  @PerfLog
  public String MyMethod() {
    // All the code I want to time.
    return whatever;
  }
}

It would seem that this is a good candidate for annotation: it is easy to add or subtract annotation; assembly assembly can completely eliminate PerfLog without having to remove annotations from the source code; An annotation handler can get class and method names.

Is it easy to do? Is there a recipe that I can follow?

It should be Java 5, so I know that I have to use apt somewhere.

+3
2

, Java. AOP, ​​ Google Guice Spring AspectJ. , AOP .

+1

AOP Spring -

, , > AOP docs : http://static.springsource.org/spring/docs/2.5.x/reference/aop.html

, .

, ( AOP AOP Spring), ( , ):

  • beans FactoryBean.
  • FactoryBean , .
  • , , , - .
  • new PerfLog() p.stop()

, AOP ( ) . , , , .. ( ).

+1

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


All Articles