其中有一個方法是這樣。
第三個參數通常是用來表示顯示時間的長短,你可能會這樣輸入。
這可能成為你的習慣了,但是如果你第三個參數亂丟一個整數的話,會怎麼樣呢?
你必須填入 Toast.LENGTH_SHORT 或是 Toast.LENGTH_LONG。
這是怎麼做到的呢? 事實上就是利用Annotation來達成的。
以下是一個簡單的範例。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MyClass { | |
public static final String STR1 = "你好"; | |
public static final String STR2 = "Hello"; | |
@StringDef({STR1 , STR2}) | |
private @interface Hi{} | |
public void Hi(@Hi String strs){ | |
} | |
} |
如果你要規範傳入方法的值,必須要是static 與 final,除了StringDef以外,還有IntDef可以使用,上面的Toast就是使用IntDef來規範。
最後就會有以下的效果
你只能輸入我規範的字串。
沒有留言:
張貼留言