码迷,mamicode.com
首页 > 其他好文 > 详细

怎样写注解?

时间:2016-10-09 20:39:59      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:注解

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

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


注解 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();
	}


怎样写注解?

标签:注解

原文地址:http://11033132.blog.51cto.com/11023132/1859908

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!