1 注解
package com.company.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NameAnnotation {
String name() default "xiaoxiao";
}
2 实体类
package com.company.common;
import com.company.annotation.NameAnnotation;
import java.io.Serializable;
public class TestClass implements Serializable {
private static final long serialVersionUID = 1377068656512767294L;
private String name;
private String address;
@NameAnnotation(name = "one")
public String annotationOne() {
return "annotation one";
}
@NameAnnotation(name = "two")
public String annotationTwo() {
return "annotation two";
}
static {
System.out.println("我是静态代码");
}
{
System.out.println("我是动态代码");
}
public TestClass() {
System.out.println("我是构造代码");
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "TestClass{" +
"name='" + name + '\'' +
", address='" + address + '\'' +
'}';
}
}
3 获取加了指定注解的方法
package com.company.reflect;
import com.company.annotation.NameAnnotation;
import com.company.common.TestClass;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class ReflectMethod {
public static void main(String[] args) {
Method[] declearedMethods = clzzUnderClassName.getDeclaredMethods();
List<String> declearedMethodsList = Stream.of(declearedMethods).map(Method::getName).collect(Collectors.toList());
System.out.println("声明的方法名:" + declearedMethodsList);
List<String> annotationDeclaredMethods = Stream.of(declearedMethods).filter(method -> method.isAnnotationPresent(NameAnnotation.class)).map(Method::getName).collect(Collectors.toList());
System.out.println("加了NameAnnotation注解的方法:" + annotationDeclaredMethods);
}
}
4 小结
- 获取加了注解的方法,通过isAnnotationPresent()方法判断当前方法是否使用了注解
- 应用场景:通过指定注解,执行对应的方法,@XxlJob注解使用了该种方式,通过调度中心,完成执行中心的定时任务