自定义Annotation

本文介绍了一个使用Java自定义注解的例子,展示了如何在运行时获取类和方法上的注解信息,并从中读取定义的属性值。
package com.test.javaSe01;

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

@Retention(value = RetentionPolicy.RUNTIME)
// 此句必须有//\u6B64\u53E5\u5FC5\u987B\u6709
@interface MySelfAnnotation {
	public int age() default 23;

	public String name() default "ctl";
}

@MySelfAnnotation(age = 100, name = "蔡腾林")
class Person {
	int age;
	String name;

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int hashCode() {
		return super.hashCode();
	}

	@MySelfAnnotation(age = 230, name = "ctllin")
	public String toString() {
		return this.name + " " + this.age;
	}

	@MySelfAnnotation
	public void print() {

	}
}

/**
 * 
 * @author Administrator
 * @deprecated 获取自定义Annotation中的值 自定义的Annotation分别定义到类和方法上
 */
public class SelfAnnotationTestDemo {
	public static void main(String[] args) {
		SelfAnnotationTestDemo sa = new SelfAnnotationTestDemo();
		Class<?> c = null;
		try {
			c = Class.forName("com.test.javaSe01.Person");
			if (c.isAnnotationPresent(MySelfAnnotation.class)) {
				MySelfAnnotation ma = c.getAnnotation(MySelfAnnotation.class);
				System.out.println(ma.name() + " " + ma.age());
			}
		} catch (ClassNotFoundException e) {
			System.err.println("com.test.javaSe01.Person没有找到");
			e.printStackTrace();
		}
		Method method = null, method1 = null;
		try {
			method = c.getMethod("toString");
			System.out.println(method);
			method1 = c.getMethod("print");
			System.out.println(method1);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		if (method.isAnnotationPresent(MySelfAnnotation.class)) {
			MySelfAnnotation myAnnotation = method
					.getAnnotation(MySelfAnnotation.class);
			int age = myAnnotation.age();
			String name = myAnnotation.name();
			System.out.println(name + " " + age);
		}
		if (method1.isAnnotationPresent(MySelfAnnotation.class)) {
			MySelfAnnotation myAnnotation = method1
					.getAnnotation(MySelfAnnotation.class);
			int age = myAnnotation.age();
			String name = myAnnotation.name();
			System.out.println(name + " " + age);
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值