簡體   English   中英

如何為自己的注釋創建可選參數?

[英]How to create optional parameters for own annotations?

下面是注釋代碼

public @interface ColumnName {
   String value();
   String datatype();
 }

我想使datatype成為可選參數,例如

@ColumnName(value="password") 

應該是一個有效的代碼。

似乎官方文檔中的第一個例子說明了一切......

/**
 * Describes the Request-For-Enhancement(RFE) that led
 * to the presence of the annotated API element.
 */
public @interface RequestForEnhancement {
    int    id();
    String synopsis();
    String engineer() default "[unassigned]"; 
    String date()     default "[unimplemented]"; 
}

要使其可選,您可以為其指定一個默認值:

public @interface ColumnName {
   String value();
   String datatype() default "String";
 }

然后在使用Annotation時不需要指定它。

對於自定義類型,您可以這樣做

public @interface SomeAnnotation {

  Class<? extends SomeInterface> yourCustomType() default SomeNullInterface.class;
  
}

/**
 * Your custom type
 */
public interface SomeInterface {

}

/**
 * Your fake null value type
 */
public interface SomeNullInterface extends SomeInterface {

}

在你的代碼中的某個地方,你可以像這樣檢查 null

if(!yourAnnotation.yourCustomType().isAssignableFrom(SomeNullInterface.class)){
  //your value is null
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM