當前位置:首頁 » 編程語言 » 自定義註解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

熱點內容
python跨模塊 發布:2025-07-30 23:04:43 瀏覽:298
阿泰編程 發布:2025-07-30 21:36:05 瀏覽:567
mybatis註解sqlif 發布:2025-07-30 21:33:59 瀏覽:570
安卓手機為什麼削不短下巴 發布:2025-07-30 21:23:13 瀏覽:493
澳洲訪問學者簽證類型 發布:2025-07-30 20:55:12 瀏覽:352
svn切換伺服器ip 發布:2025-07-30 20:43:10 瀏覽:196
匯通啟富軟體如何修改登錄密碼 發布:2025-07-30 20:41:08 瀏覽:242
公共場所的wifi密碼名稱是什麼 發布:2025-07-30 20:19:56 瀏覽:632
ios系統怎麼解壓 發布:2025-07-30 20:14:05 瀏覽:738
sqlip 發布:2025-07-30 19:20:22 瀏覽:175