Java-动态调用接口实现

时间:2025-02-13 13:50:00

目录

一、枚举类

二、接口类

三、处理不同泛型的List

四、类操作工具

五、SpringContext工具类

 


提供一个统一的对外接口,根据不同的传参,按照对应的方式处理

 

一、枚举类

定义一个枚举RequestEnum,保存method,和对应完全限定名和方法名并根据method获取到对应枚举,来进行反射获取对应类

import ;
import ;

/**
 * @Description: {枚举}
 */
@Getter
@AllArgsConstructor
public enum RequestEnum {
    GOODS_QUERY("goods_query","","xxx"),
    ORDERS_QUERY("orders__query","","xxx");

    private String method;
    private String interfaceName;
    private String methodName;

    /**
     * 获取对应枚举类型
     *
     * @param method
     * @return
     */
    public static RequestEnum getEnum(String method) {
        for (RequestEnum requestEnum : ()) {
            if (().equals(method)) {
                return requestEnum;
            }
        }
        return null;
    }

}

 

二、接口类

@PostMapping("/v1/demo")
public BaseResults demo(@RequestParam Map<String, Object> map) throws Exception {
    RequestEnum requestEnum = (("method"));
    if (requestEnum == null) {
        return new BaseResultsUtil().error(400,"参数错误");
    }
    Class<?> c = ((), ());
    Object obj = (c);

    return new BaseResultsUtil().success(().getDeclaredMethod((), ).invoke(obj, map));
}

 

三、处理不同泛型的List

使用反射机制从不同泛型的List中取出对象,并对其进行赋值

    public void exchangeList(List list) {
        for (int i = 0; i < (); i++) {
            try {
                //获取对象中名为"name"元素
                Field fields = (i).getClass().getDeclaredField("name");
                //判断该对象是否可以访问
                if (!()) {
                    //设置为可访问
                    (true);
                }
                //获取list中所有字段名为"name"的值
                (((i)).toString());

                //将list中所有字段名为“name”的值修改
                ((i), "demo");
            } catch (Exception e) {
                // TODO Auto-generated catch block
                ();
            }
        }
    }

 

四、类操作工具

import ;
import ;
import ;
import ;
import ;
import ;
import ;

import ;
import ;
import ;

/**
 * 类操作工具
 */
public class ClassUtil extends  {

    private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer();

    /**
     * 获取方法参数信息
     *
     * @param constructor    构造器
     * @param parameterIndex 参数序号
     * @return {MethodParameter}
     */
    public static MethodParameter getMethodParameter(Constructor<?> constructor, int parameterIndex) {
        MethodParameter methodParameter = new SynthesizingMethodParameter(constructor, parameterIndex);
        (PARAMETER_NAME_DISCOVERER);
        return methodParameter;
    }

    /**
     * 获取方法参数信息
     *
     * @param method         方法
     * @param parameterIndex 参数序号
     * @return {MethodParameter}
     */
    public static MethodParameter getMethodParameter(Method method, int parameterIndex) {
        MethodParameter methodParameter = new SynthesizingMethodParameter(method, parameterIndex);
        (PARAMETER_NAME_DISCOVERER);
        return methodParameter;
    }

    /**
     * 获取Annotation
     *
     * @param method         Method
     * @param annotationType 注解类
     * @param <A>            泛型标记
     * @return {Annotation}
     */
    public static <A extends Annotation> A getAnnotation(Method method, Class<A> annotationType) {
        Class<?> targetClass = ();
        // The method may be on an interface, but we need attributes from the target class.
        // If the target class is null, the method will be unchanged.
        Method specificMethod = (method, targetClass);
        // If we are dealing with method with generic parameters, find the original method.
        specificMethod = (specificMethod);
        // 先找方法,再找方法上的类
        A annotation = (specificMethod, annotationType);
        ;
        if (null != annotation) {
            return annotation;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        return ((), annotationType);
    }

    /**
     * 获取Annotation
     *
     * @param handlerMethod  HandlerMethod
     * @param annotationType 注解类
     * @param <A>            泛型标记
     * @return {Annotation}
     */
    public static <A extends Annotation> A getAnnotation(HandlerMethod handlerMethod, Class<A> annotationType) {
        // 先找方法,再找方法上的类
        A annotation = (annotationType);
        if (null != annotation) {
            return annotation;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        Class<?> beanType = ();
        return (beanType, annotationType);
    }


    /**
     * 判断是否有注解 Annotation
     *
     * @param method         Method
     * @param annotationType 注解类
     * @param <A>            泛型标记
     * @return {boolean}
     */
    public static <A extends Annotation> boolean isAnnotated(Method method, Class<A> annotationType) {
        // 先找方法,再找方法上的类
        boolean isMethodAnnotated = (method, annotationType);
        if (isMethodAnnotated) {
            return true;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        Class<?> targetClass = ();
        return (targetClass, annotationType);
    }

}

 

五、SpringContext工具类

import .slf4j.Slf4j;
import ;
import ;
import ;
import ;
import ;
import ;

/**
 * SpringContext工具类
 */
@Slf4j
@Component
public class SpringContextUtil implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext context) throws BeansException {
         = context;
    }

    /**
     * 获取bean
     *
     * @param clazz class类
     * @param <T>   泛型
     * @return T
     */
    public static <T> T getBean(Class<T> clazz) {
        if (clazz == null) {
            return null;
        }
        return (clazz);
    }

    /**
     * 获取bean
     *
     * @param beanId beanId
     * @param <T>    泛型
     * @return T
     */
    public static <T> T getBean(String beanId) {
        if (beanId == null) {
            return null;
        }
        return (T) (beanId);
    }

    /**
     * 获取bean
     *
     * @param beanName bean名称
     * @param clazz    class类
     * @param <T>      泛型
     * @return T
     */
    public static <T> T getBean(String beanName, Class<T> clazz) {
        if (null == beanName || "".equals(())) {
            return null;
        }
        if (clazz == null) {
            return null;
        }
        return (T) (beanName, clazz);
    }

    /**
     * 获取 ApplicationContext
     *
     * @return ApplicationContext
     */
    public static ApplicationContext getContext() {
        if (context == null) {
            return null;
        }
        return context;
    }

    /**
     * 发布事件
     *
     * @param event 事件
     */
    public static void publishEvent(ApplicationEvent event) {
        if (context == null) {
            return;
        }
        try {
            (event);
        } catch (Exception ex) {
            (());
        }
    }

}

 

 

 

BaseResults通用返回类:/W_Meng_H/article/details/104995823