java的自定義註解
阿新 • • 發佈:2018-12-23
2015-06-04
周海漢 2015.6.4
java 1.5以後有了自定義註解annotation。註解的作用可以用於方便看原始碼,方便編譯器理解程式碼,方便生成文件,方便執行時做一些處理。
寫程式碼測試一下
註解程式碼:
package notation;
import java.lang.annotation.*;
@Target({ElementType.METHOD, ElementType.CONSTRUCTOR }) //註解用於方法和構造
@Retention(RetentionPolicy.RUNTIME ) //註解保留到執行時,即執行時還可以反射得到
public @interface MyNotation {
String value();
}
測試程式碼
package notation;
public class TestNotation {
@MyNotation("hello world")
public void Test1(String x){
System.out.println(x);
}
@MyNotation(value="a test")
public void Test2(String x){
System.out.println(x);
}
public static void main(String[] args) {
TestNotation t = new TestNotation();
t.Test1("abloz.com");
t.Test2("abloz.com 2");
}
}
執行結果,列印:
abloz.com
abloz.com 2
如非註明轉載, 均為原創. 本站遵循知識共享CC協議,轉載請註明來源