java 注解



public @interface MyAnno {

}

public @interface MyAnno2 {
	public String schoolName();
}

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnno3 {
	public String schoolName() default "城市学院";
	
}


@MyAnno
public class Demo {
	//注解中若包含成员方法(变量)且无默认值,则必须赋值
	@MyAnno2(schoolName="hncu")
	private String name;
	
	@MyAnno3(schoolName="hncu")
	private int age2;
	
	@MyAnno
	public void t1(){
		System.out.println("11111111111");
	}
}



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;

@Inherited
@Documented
@Retention(RetentionPolicy.RUNTIME) //小心: 必须声明成RUNTIME,我们的程序才能识别MyAnno4注解
@Target({ElementType.TYPE,ElementType.METHOD})
public @interface MyAnno4 {

}
import java.lang.reflect.Method;

import cn.hncu.annotation.MyAnno3;

@MyAnno3(schoolName = "aaa")
public class Demo {
	// @MyAnno4
	private String id;

	@MyAnno4
	public void t1() {
		System.out.println("111111111111");
	}

	public static void main(String[] args) throws Exception {
		// 注解存在于class文件中,因此要通过类反射才能读取出来
		Class c = Class.forName("cn.hncu.annotation.v2.Demo");
		// 判断c中是否存在注解MyAnno4.class---注意,这只是判断类上是否有注解,Field和Method上的不算
		boolean boo = c.isAnnotationPresent(MyAnno4.class);

		// c.isAnnotation(); //判断c本身是否是一个注解
		// c.getAnnotations();//获得c中的所有注解
		System.out.println(boo);

		Method m = c.getDeclaredMethod("t1", null);
		boo = m.isAnnotationPresent(MyAnno4.class);// 判断方法m上是否有指定注解
		System.out.println("boo2:" + boo);

		// 读取注解中的成员,以当前类上的@MyAnno3注解为例
		boolean flag = c.isAnnotationPresent(MyAnno3.class);
		if (flag) {
			MyAnno3 annoObj = (MyAnno3) c.getAnnotation(MyAnno3.class);
			String name = annoObj.schoolName(); // 读取成员
			System.out.println("name:" + name);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值