Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looking for simple recipe for Java Annotation

I've never written an annotation in Java.

I've got a simple Java class for performance measurement. I call it PerfLog. Here's 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, a line will be written to the log file:

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

Can PerfLog be rewritten 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 to be a good candidate for annotating: It's easy to add or take away the annotation; a production build can leave out PerfLog entirely without having to remove the annotations from the source code; the annotation processor can get the class and method names.

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

It has to be Java 5 so I know I have to use apt somewhere.

like image 301
Mark Lutton Avatar asked Aug 05 '26 22:08

Mark Lutton


1 Answers

There is no trivial way to do this using standard Java tools. The path of least resistance would almost certainly be to use an AOP-style library like Google Guice or Spring or AspectJ. Any home-grown attempt to solve this problem will essentially end up doing what AOP libraries would already do for you.

like image 98
Mike Clark Avatar answered Aug 07 '26 14:08

Mike Clark