您的位置:首页 > 编程语言 > Java开发

Java依赖注入库框架 Dagger的源码分析(一)

2015-08-30 22:35 465 查看
1、GeneratedAdapters

对应的注释上面是这么说的:

A single point for API used in common by Adapters and Adapter generators

被Adapters以及Adapter的生产者广泛使用

通过代码,可以注意到,这是一个final类,是不允许被重载的。

他的构造函数是一个空的构造函数。

同时带有下面的常量的定义:

private static final String SEPARATOR = "$$";

public static final String INJECT_ADAPTER_SUFFIX = SEPARATOR + "InjectAdapter";

public static final String MODULE_ADAPTER_SUFFIX = SEPARATOR + "ModuleAdapter";

public static final String STATIC_INJECTION_SUFFIX = SEPARATOR + "StaticInjection";

从变量名来看,大致意思是分隔符常量字符串符号的定义,注入Adapter的后缀,模型Adapter的后缀以及静态注入的后缀。

2、ReflectiveAtInjectBinding

对应的注释上面是这么说的:

Injects the {@code @Inject}-annotated fields and constructors of a class

using reflection.

通过反射向一个class文件中注入与注解相关的成员变量的代码以及构造函数的代码

他的成员变量包含下面的部分:

private final Field[] fields;

private final ClassLoader loader;

private final Constructor<T> constructor;

private final Class<?> supertype;

private final String[] keys;

private final Binding<?>[] fieldBindings;

private final Binding<?>[] parameterBindings;

private Binding<? super T> supertypeBinding;

分别对应的是下面的描述:

1、反射中Field的数组

2、类加载器

3、反射中构造函数的对象,支持泛型

4、Class类型,支持泛型

5、key字符串数组

6、反射中成员变量Field绑定数组

7、参数绑定的数组

8、Super类型绑定的数组

在构造函数中,

对应的描述是这样的:

@param keys keys for the fields, constructor parameters and supertype in

that order. These are precomputed to minimize reflection when {@code

attach} is called multiple times.

@param constructor the injectable constructor, or null if this binding

supports members injection only.

@param supertype the injectable supertype, or null if the supertype is a

大致意思描述如下:

第一组参数key,针对成员变量Field、构造函数的参数以及超类以特定的顺序的key,这些 将会被

提前计算好,使得反射最小化,当附加的的代码被重复调用的时候。

第二个参数Constructor,可以注入的构造函数,如果绑定是仅仅支持成员的注入,那么Constructor为空指针。

在attach函数中,我们看到其中含有一个参数 Linker的对象,

从函数的主体的代码中,主要的做的事情是使用Linker的对象对成员变量、构造函数、超类的类型进行分别请求链接绑定。

在get函数中,我们可以看到是利用Constructor来创建指定泛型的一个对象。

在injectMembers的函数中,主要循环Field数组,将需要注入的对象与Field数组绑定对象中的指定的索引对象进行绑定。

通过相关的注释理解create的函数的主要的功能。

// Lookup the injectable fields and their corresponding keys.

查找可注入的成员变量以及与他们相关的keys。

// Look up @Inject-annotated constructors. If there's no @Inject-annotated

// constructor, use a default public constructor if the class has other

// injections. Otherwise treat the class as non-injectable.

查找已经注解的构造函数,如果没有已经注解的构造函数,同时这个Class有其他的注解,使用一个默认的public类型的构造函数。

要不然认为这个Class是不可以注解的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: