3. 反射(这是Java被称为动态语言的关键)

反射是什么?
反射就是在运行状态中,对于任意一个类,都能够知道这个类的属性和方法;对于任意一个对象,都能够调用的属性和方法;并且能够修改它的属性.(这是Java被称为动态语言的关键)

反射用来干什么?

  • 在运行时构造任意一个类的对象
  • 在运行时获取或修改任意一个类的成员变量
  • 在运行时候调任何一个对象的方法

反射怎么实现?

  1. 通过反射获取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);
          }
        });
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值