當前位置:首頁 » 編程語言 » 自定義註解java

自定義註解java

發布時間: 2023-07-01 20:09:34

java ,自定義註解怎麼使用

java中自定義註解的使用方法:
首先聲明一個介面,並未它添加註解內容!
package testAnnotation;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Documented
@Retention(RetentionPolicy.RUNTIME)
public @interface Person{
String name();
int age();
}
2、然後利用反射機制查看類的註解內容
package testAnnotation;

@Person(name="xingoo",age=25)
public class test3 {
public static void print(Class c){
System.out.println(c.getName());

//java.lang.Class的getAnnotation方法,如果有註解,則返回註解。否則返回null
Person person = (Person)c.getAnnotation(Person.class);

if(person != null){
System.out.println("name:"+person.name()+" age:"+person.age());
}else{
System.out.println("person unknown!");
}
}
public static void main(String[] args){
test3.print(test3.class);
}
}
運行結果,讀取到了註解的內容
testAnnotation.test3
name:xingoo age:25

熱點內容
java面試的演算法題 發布:2025-05-14 04:06:18 瀏覽:467
交叉編譯優化 發布:2025-05-14 03:48:52 瀏覽:532
動圖在線壓縮 發布:2025-05-14 03:35:24 瀏覽:133
w7共享無法訪問 發布:2025-05-14 03:35:24 瀏覽:483
為什麼微信會出現賬號密碼錯誤 發布:2025-05-14 03:03:30 瀏覽:693
幻影腳本官網 發布:2025-05-14 03:01:13 瀏覽:827
servlet的webxml怎麼配置 發布:2025-05-14 02:51:46 瀏覽:773
怎麼取消手勢密碼 發布:2025-05-14 02:51:11 瀏覽:640
openvpn搭建vpn伺服器搭建 發布:2025-05-14 02:47:52 瀏覽:999
密碼忘了從哪裡找 發布:2025-05-14 02:39:09 瀏覽:548