繁体   English   中英

Java中的自定义注释

[英]Custom Annotations in Java

这是我第一次尝试在Java中编写自定义注释。

我不确定是否有可能,但是想在尝试其他解决方案之前先尝试一下。

因此,在这种情况下,我有很多方法可以将数据从应用程序发送到设备。 我需要将所有这些数据记录在数据库中。

我想为此创建一个注释,以便可以在注释中编写代码以将数据记录到数据库中,然后使用此注释对所有方法进行注释。

我可以修改代码以登录到数据库,但是在那种情况下,我必须进入每种方法并将代码放置在正确的位置,以便将它们登录到数据库。

这就是我正在寻找基于注释的方法的原因。

我可能正在寻找什么,还是我要求更多?

任何指点将不胜感激,或者如果有人对我的解决方案采用不同的方法,那将确实有帮助。

不用编写自己的注释并进行处理,而是查看Spring提供的内容,例如Interceptors:

春季拦截器与方面?

您可以尝试以下方法

包装注释;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
    public enum Priority {LOW, MEDIUM, HIGH}
    String logInfo() default "Logging...";
    Priority priority() default Priority.LOW;
}


package annotation;

public class BusinessLogic {
    public BusinessLogic() {
        super();
    }

    public void compltedMethod() {
        System.out.println("This method is complete");
    }    

    @Todo(priority = Todo.Priority.HIGH)
    public void notYetStartedMethod() {
        // No Code Written yet
    }

    @Todo(priority = Todo.Priority.MEDIUM, logInfo = "Inside DAO")
    public void incompleteMethod1() {
        //Some business logic is written
        //But its not complete yet
    }

    @Todo(priority = Todo.Priority.LOW)
    public void incompleteMethod2() {
        //Some business logic is written
        //But its not complete yet
    }
}


package annotation;
import java.lang.reflect.Method;

public class TodoReport {
    public TodoReport() {
        super();
    }

    public static void main(String[] args) {
        Class businessLogicClass = BusinessLogic.class;
        for(Method method : businessLogicClass.getMethods()) {
            Todo todoAnnotation = (Todo)method.getAnnotation(Todo.class);
            if(todoAnnotation != null) {
                System.out.println(" Method Name : " + method.getName());
                System.out.println(" Author : " + todoAnnotation.logInfo());
                System.out.println(" Priority : " + todoAnnotation.priority());
                System.out.println(" --------------------------- ");
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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