java5新特性之Annotation 注解

 一、注解是jdk1.5后加入的新特性,jdk自带的Annotation类主要有三个:

      @SuppressWarnings,可用于隐藏一些警告的提示.

       

      

      用@SuppressWarnings注解后:

      

       其实还可以用泛型消除:

   

public List<GirlFriend> getGirlFriends(){
	    List<GirlFriend> list = new ArrayList<GirlFriend>();
	    for(int i=0 ;i<10;i++){
	    GirlFriend gf = new GirlFriend();
	    list.add(gf);
	    }
	    return list;
}

 

    指明集合里要装的元素类型

 

      @Deprecated,此注解可作用在类、属性及方法上.用来说明这个类、属性或方法不再建议使用.

 

      @Override,作用于方法上,是让编译器检查这个方法是不是重写了父类的方法,如果没有,则编译会报错。这样可以避免由于程序员不小心敲错或敲漏字母造成的错误!

 

二、自定义Annotation

     1、定义注解类MyAnnotation

     

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String value() default "test";
	EnumTest value1() default EnumTest.Welcome;
}

 @Retention(RetentionPolicy.RUNTIME)的作用是标志MyAnnotation 注解信息保留到运行期间。这样才能使用反射获取该注解的信息.

     2、应用了"注解类"的类

@MyAnnotation(value1=EnumTest.Hello)  //如果有默认值可不填参数  @MyAnnotation
public class Test {
          @MyAnnotation(value="hello world",value1=EnumTest.Welcome)
           public static void test(){
		System.out.println("调用了test()方法");
	}
}

 

     3、对"应用了注解类的类"进行反射操作的类

 

 

public class MyReflection {
	public static void main(String[] args) 
	throws IllegalArgumentException, IllegalAccessException, 
	InvocationTargetException, SecurityException, NoSuchMethodException{
		Class<Test> clazz = Test.class;
		Method method = clazz.getMethod("test",new Class[]{});
		if(method.isAnnotationPresent(MyAnnotation.class)){
				method.invoke(clazz, new Object[]{});//用类clazz调用的是一个静态方法
			MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
			System.out.println(anno.annotationType());
			System.out.println(anno.value());
			System.out.println(anno.value1());
			Method[] ms = anno.annotationType().getDeclaredMethods();
			for(Method m : ms){
				System.out.println(m.getName());
			}
		}
	}
}

 

 

 打印结果:

调用了test()方法
interface annotation.MyAnnotation
hello world
Welcome
value1
value

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值