Java注解Annotation学习笔记
一、自定义注解
1. 使用关键字 @interface
2. 默认情况下,注解可以修饰 类、方法、接口等。
3. 如下为一个基本的注解例子:
//注解中的成员变量非常像定义接口public @interface MyAnnotation {//不带有默认值String name();//带有默认值int age() default 20;}
4. Reflect中3个常见方法解读
- getAnnotion(Class<T> annotationClass) 返回该元素上存在的,指定类型的注解,如果没有返回null
- Annotation[] getAnnotations() 返回该元素上所有的注解。
- boolean isAnnotationPersent(Class<? extends Annotation> annotationClass) 判断该院上上是否含有制定类型的注释。
二、元注解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface ValueBind {filedType type();String value() default "SUSU";enum filedType {STRING, INT}}
其中@Target 和 @Retention为元注解。
- @Retention有如下几种取值:
![]()
- 其中通常都是RetentionPolicy.RUNTIME
@Target有如下几个取值:

@Inherited 表示该注解具有继承性。
三、Demo
1. ValueBind注解
@Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface ValueBind {filedType type();String value() default "SUSU";enum filedType {STRING, INT}}
2. Person类
public class Person implements Serializable {private String name;private int age;public String getName() {return name;}@ValueBind(type = ValueBind.filedType.STRING, value = "LCF")public void setName(String name) {this.name = name;}public int getAge() {return age;}@ValueBind(type = ValueBind.filedType.INT, value = "21")public void setAge(int age) {this.age = age;}@Overridepublic String toString() {return "Person{" +"name='" + name + '\'' +", age=" + age +'}';}}
3. Main方法
import java.lang.reflect.Method;public class Main {public static void main(String[] args) throws Exception {Object person = Class.forName("Person").newInstance();//以下获取的是:类的注解// Annotation[] annotations = person.getClass().getAnnotations();Method[] methods = person.getClass().getMethods();for (Method method : methods) {//如果该方法上面具有ValueBind这个注解if (method.isAnnotationPresent(ValueBind.class)) {//通过这个注解可以获取到注解中定义的ValueBind annotation = method.getAnnotation(ValueBind.class);if (annotation.type().equals(ValueBind.filedType.STRING)) {method.invoke(person, annotation.value());} else {method.invoke(person, Integer.parseInt(annotation.value()));}}}System.out.println(person);}}
输出结果:
Person{name='LCF', age=21}
Doing is better than nothing


浙公网安备 33010602011771号