proxy代理实现接口调用处理

proxy代理实现接口调用处理

我们知道,要调用接口必须要实例化才能调用。
那么我们能不能不实例化调用呢?像mybatis、hibernate那样定义一个接口就能注入调用。其实他们的底层实现就是用代理模式 proxy:
在不实例化的情况下调用接口(实际上代理实例化了)

首先定义一个注解用来区别

import java.lang.annotation.*;

/**
 * @author lingkang
 * Created by 2022/5/4
 * mapper 查询注解
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Select {
    /**
     * 查询语句 SQL
     */
    String value() default "";
}

再编写一个调用接口

import java.util.Map;

/**
 * @author lingkang
 * Created by 2022/5/4
 */
public interface MyMapper {
    @Select("select * from user where id=?")
    Map select(Integer id);
}

然后定义代理调用处理类

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lingkang
 * Created by 2022/5/4
 */
public class MyInvocationHandler implements InvocationHandler, Serializable {
    private Class<?> clazz;

    public MyInvocationHandler(Class<?> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Method exMethod = clazz.getMethod(method.getName(), getClassTypes(args));
        if (args[0].getClass().isArray()) {
            args = (Object[]) args[0];
            if (args.length == 0)
                args = null;
        }
        Select select = exMethod.getAnnotation(Select.class);
        System.out.println("查询SQL:" + select.value());
        System.out.println("参数: " + args[0]);

        // 接口需要返回的结果类型
        //Class<?> returnType = exMethod.getReturnType();
        Class<?> returnType = getReturnType(exMethod);
        System.out.println("接口需要返回的结果类型: " + returnType);
        Map map = new HashMap();
        map.put("result", "hello lingkang!");
        System.out.println("假设在此执行SQL返回结果:");
        return map;
    }

    // 有时可能需要特殊处理
    public static Class<?> getReturnType(Method method) {
        Type returnType = method.getGenericReturnType();
        if (returnType instanceof ParameterizedType) {
            ParameterizedType type = (ParameterizedType) returnType;
            return (Class<?>) type.getActualTypeArguments()[0];
        } else if ("void".equals(returnType.getTypeName())) {
            return null;
        }
        return Map.class;
    }

    public static Class<?>[] getClassTypes(Object[] args) {
        Class[] clazz = new Class[args.length];
        for (int i = 0; i < args.length; i++)
            clazz[i] = args[i].getClass();
        return clazz;
    }
}

调用这个代理处理

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;

/**
 * @author lingkang
 * Created by 2022/5/4
 */
public class Demo01 {
    public static void main(String[] args) {
        // 获取接口代理
        MyMapper mapper = getMapper(MyMapper.class, new MyInvocationHandler(MyMapper.class));
        // 调用
        System.out.println("调用结果:"+mapper.select(1));
    }

    /**
     * 代理实例化
     */
    public static <T> T getMapper(Class<T> clazz, InvocationHandler handler) {
        return (T) Proxy.newProxyInstance(
                clazz.getClassLoader(),
                new Class[]{clazz},
                handler);
    }
}

结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌康ACG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值