代理
本章讲的代理将和Retrofit里面的代码结合讲,有目的的讲。
Proxy未有讲到的请忽略。 :sunglasses: :sunglasses: :sunglasses:
贴上代码如下:
package com.rulang.proxy;
import sun.plugin.javascript.navig.LinkArray;
import java.util.ArrayList;
import java.util.List;
/**
* Created by rulang on 2017/8/24.
*/
public interface ProxyInterFace {
public ArrayList<String> callProxy();
}
package com.rulang.proxy;
import java.lang.reflect.*;
import java.util.ArrayList;
/**
* Created by rulang on 2017/8/24.
*/
public class ProxyInvocationHandler implements InvocationHandler {
public ProxyInvocationHandler(){
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(proxy instanceof ProxyInterFace) {
ParameterizedType t2= (ParameterizedType) method.getGenericReturnType();
System.out.println(t2.getRawType());//输出:class java.util.ArrayList
System.out.println(t2.getActualTypeArguments()[0]);// class java.lang.String
}
return new ArrayList<String>(); // 如果此处返回对象,应该是一个ArrayList<String>
// return method.invoke(proxy);
}
}
package com.rulang.proxy;
import sun.reflect.generics.reflectiveObjects.GenericArrayTypeImpl;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.ArrayList;
/**
* Created by rulang on 2017/8/24.
*/
public class Sunglasses {
public static void main(String[] jiexieQi) throws Exception {
ProxyInterFace proxy= (ProxyInterFace) Proxy.newProxyInstance(Sunglasses.class.getClassLoader(),
new Class[]{ProxyInterFace.class},new ProxyInvocationHandler());
ArrayList<String> data= proxy.callProxy();
}
}
此处有个有趣的事情,在我上学的时候,虽然在睡觉,但是老师一直讲interface不能实例化。
对此深深引入脑海了,但是在这个里面并没有对ProxyInterFace做任何的实现。却依然能实例化。
这就是代理的功劳,要不在proxy.callProxy()调用的时候,应该会报错的。
我这里只是引入相关概念,Proxy很强悍,也是一种设计模式。
下一章,Retrofit开讲。。。