简体   繁体   中英

Create custom annotation in Java and use it when a method is called

What I want to do is to create a custom annotation to use it on a Service, and each time a method is called from there first execute something. For example:

@CustomAnnotation
public Class MyService{

   public void myMethod(){
      //do something
   }
}

And when myMethod is called, do something before its code is executed, and then do what it has to do. Is there any way to do that? I need to do it with annotations, using interfaces or inheritance for that is useless because is for each method, not just one.

I know how to scan a package to get the classes annotated, but I don't know how to check it at runtime when the app is running.

Thank you!

It seems that what you need may be achieved by using AOP (aspect oriented programming).

Ive posted the code example here . It executes some code before the annotated methods and doesn't execute for others.

AOP allows you to do that without intervention in code of method-containing classes, you may alter methods behavior without altering methods themselves and their invocation code. You may even skip method execution using this technique (using @Around advice). It is useful if you need security checks before allowing method execution, for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM