簡體   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