通过继承来实现注解方式的属性注入

要使用注解来注入属性,首先就要定义一个注解,注解的定义如下:

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;

/*四个元注解,他们的意思 (个人记忆)依次是 生成文档 可以被子类使用 在运行时可以使用 注解的目标是FIELD*/
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotion {
	//有一个名为VALUE的值,默认为123
	String value() default "123";
}

package everyworkdayprogramming._2015_1_23;

import java.lang.reflect.Field;

public class SuperClass {
	// 在我们的父类的默认构造方法中来进行属性注入的操作,这里利用了子类会默认调用父类的无参构造方法的特性
	public SuperClass() {
		//获得类中的所有的属性
		Field[] fields = this.getClass().getDeclaredFields();
		//遍历fields
		for (Field field : fields) {
			//如果这个field有注解MyAnnotion
			if (field.isAnnotationPresent(MyAnnotion.class)) {
				//获得field对应的MyAnnotion实例
				MyAnnotion myAnnotion = field.getAnnotation(MyAnnotion.class);
				try {
					//因为field是私有属性,所以要设置这里
					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 {
	// 调用注解注入属性,默认值是123,这里设置为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());
	}
}


posted @ 2015-02-14 10:23  qz程程  阅读(720)  评论(0编辑  收藏  举报