注释: 给其它开发人员阅读

注解:给程序阅读的注释 ----  取代配置文件


注解 Java5新特性

@Override: 限定重写父类方法, 该注解只能用于方法

@Deprecated: 用于表示某个程序元素(, 方法等)已过时

@SuppressWarnings: 抑制编译器警告

//限定该注解仅仅可以作用在方法
@Target(ElementType.METHOD)
// 注解生效的时间
@Retention(RetentionPolicy.RUNTIME)
public @interface PersonInfo {
	String[] food();
}

注意事项:

       1 注解属性可以是哪些类型?

        String、基本数据类型、enumClass 、其它注解类型、以上数据类型相应一维数组

 

    2 特殊属性 value

           在应用注解时,需要为注解每个属性赋值(有默认值可以忽略



使用注解:反射

@PersonInfo(food = { "juice", "beer" })
	public void drink() {
		// 拿到字节码对象
		Class clazz = this.getClass();
		// 拿到其中的方法
		Method method;
		try {
			method = clazz.getDeclaredMethod("drink");
			boolean flag = method.isAnnotationPresent(PersonInfo.class);
			if (!flag) {
				System.out.println(this.name + "没得喝");
				return;
			}
			PersonInfo info = method.getAnnotation(PersonInfo.class);
			String[] food = info.food();
			System.out.println(this.name + "喝" + Arrays.toString(food));
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		Person p = new Person();
		p.setName("ann");
		p.drink();
	}