當(dāng)前位置:
首頁 >
通过继承来实现注解方式的属性注入
發(fā)布時(shí)間:2025/3/15
57
豆豆
生活随笔
收集整理的這篇文章主要介紹了
通过继承来实现注解方式的属性注入
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
要使用注解來注入屬性,首先就要定義一個(gè)注解,注解的定義如下:
package everyworkdayprogramming._2015_1_23;import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target;/*四個(gè)元注解,他們的意思 (個(gè)人記憶)依次是 生成文檔 可以被子類使用 在運(yùn)行時(shí)可以使用 注解的目標(biāo)是FIELD*/ @Documented @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) public @interface MyAnnotion {//有一個(gè)名為VALUE的值,默認(rèn)為123String value() default "123"; }package everyworkdayprogramming._2015_1_23;import java.lang.reflect.Field;public class SuperClass {// 在我們的父類的默認(rèn)構(gòu)造方法中來進(jìn)行屬性注入的操作,這里利用了子類會(huì)默認(rèn)調(diào)用父類的無參構(gòu)造方法的特性public SuperClass() {//獲得類中的所有的屬性Field[] fields = this.getClass().getDeclaredFields();//遍歷fieldsfor (Field field : fields) {//如果這個(gè)field有注解MyAnnotionif (field.isAnnotationPresent(MyAnnotion.class)) {//獲得field對應(yīng)的MyAnnotion實(shí)例MyAnnotion myAnnotion = field.getAnnotation(MyAnnotion.class);try {//因?yàn)閒ield是私有屬性,所以要設(shè)置這里field.setAccessible(true);//修改field的值為annotion中注入的值field.set(this, myAnnotion.value());} catch (IllegalArgumentException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}}} }
package everyworkdayprogramming._2015_1_23;/*子類直接繼承我們的父類*/ public class SubClass extends SuperClass {// 調(diào)用注解注入屬性,默認(rèn)值是123,這里設(shè)置為test@MyAnnotion(value = "test")private String num;public String getNum() {return num;}public void setNum(String num) {this.num = num;}public static void main(String[] args) {// 輸出一下我們的屬性值System.out.println(new SubClass().getNum());} }
總結(jié)
以上是生活随笔為你收集整理的通过继承来实现注解方式的属性注入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vsphere client中部署OVF
- 下一篇: [读书笔记] 代码整洁之道