Java-动态调用接口实现

64 篇文章 1 订阅
56 篇文章 2 订阅

目录

一、枚举类

二、接口类

三、处理不同泛型的List

四、类操作工具

五、SpringContext工具类

 


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

 

一、枚举类

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

import lombok.AllArgsConstructor;
import lombok.Getter;

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

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

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

}

 

二、接口类

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

    return new BaseResultsUtil().success(obj.getClass().getDeclaredMethod(requestEnum.getMethodName(), Map.class).invoke(obj, map));
}

 

三、处理不同泛型的List

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

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

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

 

四、类操作工具

import org.springframework.core.BridgeMethodResolver;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.MethodParameter;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.core.annotation.SynthesizingMethodParameter;
import org.springframework.web.method.HandlerMethod;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * 类操作工具
 */
public class ClassUtil extends org.springframework.util.ClassUtils {

    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);
        methodParameter.initParameterNameDiscovery(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);
        methodParameter.initParameterNameDiscovery(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 = method.getDeclaringClass();
        // 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 = ClassUtil.getMostSpecificMethod(method, targetClass);
        // If we are dealing with method with generic parameters, find the original method.
        specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
        // 先找方法,再找方法上的类
        A annotation = AnnotatedElementUtils.findMergedAnnotation(specificMethod, annotationType);
        ;
        if (null != annotation) {
            return annotation;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        return AnnotatedElementUtils.findMergedAnnotation(specificMethod.getDeclaringClass(), 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 = handlerMethod.getMethodAnnotation(annotationType);
        if (null != annotation) {
            return annotation;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        Class<?> beanType = handlerMethod.getBeanType();
        return AnnotatedElementUtils.findMergedAnnotation(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 = AnnotatedElementUtils.isAnnotated(method, annotationType);
        if (isMethodAnnotated) {
            return true;
        }
        // 获取类上面的Annotation,可能包含组合注解,故采用spring的工具类
        Class<?> targetClass = method.getDeclaringClass();
        return AnnotatedElementUtils.isAnnotated(targetClass, annotationType);
    }

}

 

五、SpringContext工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

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

    private static ApplicationContext context;

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

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

    /**
     * 获取bean
     *
     * @param beanId beanId
     * @param <T>    泛型
     * @return T
     */
    public static <T> T getBean(String beanId) {
        if (beanId == null) {
            return null;
        }
        return (T) context.getBean(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(beanName.trim())) {
            return null;
        }
        if (clazz == null) {
            return null;
        }
        return (T) context.getBean(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 {
            context.publishEvent(event);
        } catch (Exception ex) {
            log.error(ex.getMessage());
        }
    }

}

 

 

 

BaseResults通用返回类:https://blog.csdn.net/W_Meng_H/article/details/104995823

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值