Writing a java annotation for timing method call

后端 未结 9 1405
逝去的感伤
逝去的感伤 2020-12-24 12:17

I want to write a java annotation which times the method call. something like this:

@TimeIt
public int someMethod() { ... }

and when this m

9条回答
  •  失恋的感觉
    2020-12-24 12:49

    Despite all the nay-sayers, you can do this. Java annotations cannot change the source or class files they operate on, so your options are:

    1) Use a super class. The annotation processor can generate a super-class that times an abstract method. Your actual class implements this method. The downsides is that the method you want to time has to be renamed so that the super-class can provide an implementation. The result might look like this

    @BenchmarkMe( extend="MySuperClass" )
    public class MyClass extends BenchmarkMyClass {
        public void normalMethod() { ... }
        public void bench_myMethod() { ... }
    }  
    

    and the annotation process would generate:

    public class BenchmarkMyClass extends MySuperClass {
        public abstract void bench_myMethod();
        public void myMethod() {
           benchmarkStart();
           try {
              bench_myMethod();
           } finally { benchmarkStop(); }
        }
    }
    

    By using a naming convention to indicate which methods should be timed as the prefix "bench_" was used in my example.

    2) Use a ClassFileTranformer as well as an Annotation The approach would be to create a runtime annotation that can be used to mark the methods you are interested in timing. At runtime a ClassFileTransformer is specified on the command line and it transforms the byte code to insert the timing code.

    Unless you like working with byte code, using AOP is the better bet, but it IS possible.

提交回复
热议问题