标签:Object Java args list 代理 接口 class new public
介绍
模仿 Mybatis 的接口代理,自己模仿写一下。
接口
public interface MyInterface { public List<String> getString(String a, String b); }
代理(未做到通用)
public class MyProxy<T> implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { ArrayList list = new ArrayList(); list.add(args[0]); list.add(args[1]); return list; } }
代理工厂
public class ProxyFactory { public <T> T getProxyInstance(MyProxy<T> myProxy, Class<T> target){ ClassLoader classLoader = myProxy.getClass().getClassLoader(); return (T)Proxy.newProxyInstance(classLoader, new Class[] { target }, myProxy); } }
测试
public class Mytest { public static void main(String[] args) { ProxyFactory proxyFactory = new ProxyFactory(); MyInterface myInterface = proxyFactory.getProxyInstance(new MyProxy<MyInterface>(), MyInterface.class); List<String> string = myInterface.getString("fei", "gege"); System.out.println(string.toString()); } }
结果:[fei, gege]
标签:Object,Java,args,list,代理,接口,class,new,public
来源: https://www.cnblogs.com/feiqiangsheng/p/16412201.html