自定义注解及其使用方法

自定义注解

package com.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 自定义注解
@Documented
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
@Retention(value = RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
	String value();
	int age();
}
@SuppressWarnings({ "unused", "rawtypes" })//压制警告的注解

自定义注解使用

package com.annotation;

// 自定义注解使用
@MyAnnotation(value = "jock", age = 20)
class Teacher {
	@MyAnnotation(value = "hpeu", age = 20)
	private String name;
	@MyAnnotation(value = "ty", age = 20)
	public void show() {
		System.out.println("show");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
public class MyAnnotationTest {
	public static void main(String[] args) {
		Teacher teacher = new Teacher();
		MyAnnotation annotation = teacher.getClass()
				.getAnnotation(MyAnnotation.class);
		System.out.println(annotation.value());
	}
}

你可能感兴趣的:(java)