1、创建注解
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface HttpMapping {
@AliasFor("path")
String[] value() default {};
}
2、存储结构
public class RunMethod {
//调用类
public Object choseClass;
//类中的方法
public Method method;
public RunMethod(Object choseClass, Method method) {
this.choseClass = choseClass;
this.method = method;
}
public Object run(Object... args){
try {
return method.invoke(choseClass,args);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
3、通过路径找注解或者类的,工具类
public final class ClassUtils {
/**
* 是否有注解
*
* @param clazz a {@link Class} object.
* @param annotationClass a {@link Class} object.
* @return a boolean.
*/
public static boolean hasClassAnnotation(Class<?> clazz,
Class<? extends Annotation> annotationClass) {
return getClassAnnotation(clazz, annotationClass) != null;
}
/**
* 是否有注解
*
* @param clazz a {@link Class} object.
* @param annotationClass a {@link Class} object.
* @param fieldName a {@link String} object.
* @return a boolean.
* @throws Exception if any.
*/
public static boolean hasFieldAnnotation(Class<?> clazz,
Class<? extends Annotation> annotationClass, String fieldName)
throws Exception {
return getFieldAnnotation(clazz, annotationClass, fieldName) != null;
}
/**
* 是否有注解
*
* @param clazz a {@link Class} object.
* @param annotationClass a {@link Class} object.
* @param methodName a {@link String} object.
* @param paramType a {@link Class} object.
* @return a boolean.
*/
public static boolean hasMethodAnnotation(Class<?> clazz,
Class<? extends Annotation> annotationClass, String methodName,
Class<?>... paramType) throws Exception {
return getMethodAnnotation(clazz, annotationClass, methodName,
paramType) != null;
}
/**
* 获取类注解
*
* @param clazz 类
* @param annotationClass 注解类
* @return a A object.
*/
public static <A extends Annotation> A getClassAnnotation(Class<?> clazz,
Class<A> annotationClass) {
// Annotation[] annotations = clazz.getAnnotations();
// for (Annotation annotation : annotations) {
// if (annotation.getClass() == annotationClass) {
// return (A) annotation;
// } else {
// Annotation anno = getClassAnnotation(annotation