反射是什么?
反射就是在运行状态中,对于任意一个类,都能够知道这个类的属性和方法;对于任意一个对象,都能够调用的属性和方法;并且能够修改它的属性.(这是Java被称为动态语言的关键
)
反射用来干什么?
- 在运行时构造任意一个类的对象
- 在运行时获取或修改任意一个类的成员变量
- 在运行时候调任何一个对象的方法
反射怎么实现?
- 通过反射获取Class对象的三种方式:
- 通过类名获取 如:
Person.class
- 通过对象获取 如:
mPerson.getClass()
- 通过全类名获取 如:
Class.forName("com.tangkun.reflect.Person")
和
classLoader.loadClass("com.tangkun.reflect.Person")
2.创建实例
通过反射创建对象的两种方式:
Person p = (Person)(class.newInstance());
Constructor constructor = class.getConstructor();
Person p = (Person)(constructor.newInstance());
反射的应用: retrofit
框架
retrofit
框架使用到了动态代理、反射和注解技术;
retrofit
是对HTTP
网络请求框架的封装,网络请求的工作本质是由OkHttp
完成的,而Retrofit
仅负责网络请求接口的封装.
//初始化retrofit
Retrofit retrofit = new Retrofit.Builder().baseUrl("https://restapi.amap.com").build();
//创建接口调用类,这里的create方法就用到了动态代理
//WeatherApi接口类中就使用到了带有注解接口方法和参数
//然后create方法传递的参数WeatherApi.class即用到了反射
WeatherApi weatherApi = retrofit.create(WeatherApi.class);
Call<ResponseBody> call = weatherApi.getWeather("110101", "ae6c53e2186f33bbf240a12d80672d1b");
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
//Retrofit的create方法源码,里面用到了动态代理
public <T> T create(final Class<T> service) {
validateServiceInterface(service);
return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class<?>[] { service },
new InvocationHandler() {
private final Platform platform = Platform.get();
private final Object[] emptyArgs = new Object[0];
@Override public @Nullable Object invoke(Object proxy, Method method,
@Nullable Object[] args) throws Throwable {
// If the method is a method from Object then defer to normal invocation.
if (method.getDeclaringClass() == Object.class) {
return method.invoke(this, args);
}
if (platform.isDefaultMethod(method)) {
return platform.invokeDefaultMethod(method, service, proxy, args);
}
return loadServiceMethod(method).invoke(args != null ? args : emptyArgs);
}
});
}