java反射和注解
目錄
- 反射
- 注解
- 元屬性
- 自定義注解
- 使用案例
反射
Class<?> aClass = Class.forName("reflect.Student"); Constructor<?> constructor = aClass.getConstructor();//構(gòu)造函數(shù),用于創(chuàng)建對象 Object obj = constructor.newInstance(); //創(chuàng)建對象,用于執(zhí)行函數(shù)Method[] methods = aClass.getMethods();//獲取方法 for (Method method : methods) {System.out.println(method); } Method out = aClass.getMethod("out");//獲取指定方法 out.invoke(obj);//執(zhí)行方法Field[] fields = aClass.getDeclaredFields();//獲取所有屬性(包括private) for (Field field : fields) {System.out.println(field.getName()); } fields[0].setAccessible(true); //給屬性解鎖 fields[0] private name; fields[0].set(obj, "小明"); //給屬性賦值 System.out.println(obj);//獲取注解 Class<BookStore> bookStoreClass = BookStore.class; Method buyBook = bookStoreClass.getMethod("buyBook"); //判斷是否有注解,如果用buyBook則獲取的是類上的注解 if (bookStoreClass.isAnnotationPresent(Book.class)) {Book annotation = bookStoreClass.getAnnotation(Book.class);//輸出注解System.out.println(annotation.value());System.out.println(Arrays.toString(annotation.authors())); }注解
元屬性
@Target ElemenetType: TYPE:用在類,接口上 FIELD:用在成員變量上 METHOD用在方法上 PARAMETER:用在參數(shù)上 CONSTRUCTOR:用在構(gòu)造方法上 LOCAL_VARIABLE:用在局部變量上@Retention RetentionPolicy: SOURCE:注解只存在于Java源代碼中,編譯生成的字節(jié)碼文件中就不存在了。 CLASS:注解存在于Java源代碼、編譯以后的字節(jié)碼文件中,運(yùn)行的時候內(nèi)存中沒有,默認(rèn)值。 RUNTIME:注解存在于Java源代碼中、編譯以后的字節(jié)碼文件中、運(yùn)行時內(nèi)存中,程序可以通過反射獲取該注解。自定義注解
@Target({ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Book {// 當(dāng)注解中只有一個屬性且名稱是value,在使用注解時給value屬性賦值可以直接給屬性值//書名String value();//價格double price() default 100;//作者String[] authors(); }使用案例
@Book(value = "紅樓夢",authors = "曹雪芹",price = 998) public class BookStore {@Book(value = "西游記",authors = {"吳承恩"})public void buyBook(){} }轉(zhuǎn)載于:https://www.cnblogs.com/birdofparadise/p/9769293.html
總結(jié)