服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

classworking 工具箱: 反射泛型

  java™ 5 扩展了 java 语言类型系统以支持类、方法和值的参数化类型。参数化的类型通过确保使用正确的类型及消除从源代码进行类型转换提供了重要的编译时好处。除了这些编译时好处,类型信息对于 classworking 工具操纵 java 代码也有帮助。在本文中,jibx 首席开发员 dennis sosnoski 分析了如何用反射深入参数化类型的内部,并充分展示了 java 5 应用程序数据结构的优势。

  许多工具都是围绕使用 java 反射而设计的,它们的用途包括从用数据值填充 gui 组件到在运行的应用程序中动态装载新功能。反射对于在运行时分析数据结构特别有用,许多在内部对象结构与外部格式(包括 xml、数据库和其他持久化格式)之间转换的框架都基于对数据结构的反射分析。

  使用反射分析数据结构的一个问题是标准 java 集合类(如 java.util.arraylist)对于反射来说总是“死胡同(dead-end)” ―― 到达一个集合类后,无法再访问数据结构的更多细节,因为没有关于集合中包含的项目类型的信息。java 5 改变了这一情况,它增加了对泛型的支持,将所有集合类转换为支持类型的泛型形式。java 5 还扩展了反射 api ,支持在运行时对泛型类型信息进行访问。这些改变使反射可以比以往更深入地挖掘数据结构。

包装之下代码

  许多文章讨论了 java 5 的泛型功能的使用。对于本文,假定您已经了解泛型的基本知识。我们首先使用一些示例代码,然后直接讨论如何在运行时访问泛型信息。

  作为使用泛型的一个例子,我准备使用一个表示一组路径中的目录和文件的数据结构。清单 1 给出了这个数据结构根类的代码。pathdirectory 类取路径 string 数组作为构造函数参数。这个构造函数将每一个字符串解释为目录路径,并构造一个数据结构以表示这个路径下面的文件和子目录。处理每一路径时,这个构造函数就将这个路径和这个路径的数据结构加到一个成对集合(pair collection)中。

清单 1. 目录信息集

public class pathdirectory implements iterable{    private final paircollection m_pathpairs;        public pathdirectory(string[] paths) {        m_pathpairs = new paircollection();        for (string path : paths) {            file file = new file(path);            if (file.exists() && file.isdirectory()) {                dirinfo info = new dirinfo(new file(path));                m_pathpairs.add(path, info);            }        }    }    public paircollection.pairiterator iterator() {        return m_pathpairs.iterator();    }        public static void main(string[] args) {        pathdirectory inst = new pathdirectory(args);        paircollection.pairiterator iter = inst.iterator();        while (iter.hasnext()) {            string path = iter.next();            dirinfo info = iter.matching();            system.out.println("directory " + path + " has " +                info.getfiles().size() + " files and " +                info.getdirectories().size() + " child directories");        }    }}

  清单 2 给出了 paircollection 的代码。这个泛型类处理成对的值,类型参数给出了这些对中项目的类型。它提供了一个 add() 方法向集合中加入一个元组(tuple),一个 clear() 方法清空集合中所有元组,一个 iterator() 方法返回遍历集合中所有对的迭代器。内部 pairiterator 类实现由后一个方法返回的特殊迭代器,它定义了一个额外的 matching() 方法,这个方法用于得到由标准 next() 方法返回的值的配对(第二个)值。


清单 2. 泛型对集合

public class paircollection implements iterable{    // code assumes random access so force implementation class	  private final arraylist m_tvalues;    private final arraylist m_uvalues;        public paircollection() {		    m_tvalues = new arraylist();        m_uvalues = new arraylist();    }        public void add(t t, u u) {        m_tvalues.add(t);        m_uvalues.add(u);    }        public void clear() {        m_tvalues.clear();        m_uvalues.clear();    }    public pairiterator iterator() {        return new pairiterator();    }        public class pairiterator implements iterator    {        private int m_offset;        public boolean hasnext() {            return m_offset < m_tvalues.size();        }        public t next() {            if (m_offset < m_tvalues.size()) {                return m_tvalues.get(m_offset++);            } else {                throw new nosuchelementexception();            }        }        public u matching() {            if (m_offset > 0) {                return m_uvalues.get(m_offset-1);            } else {                throw new nosuchelementexception();            }        }        public void remove() {            throw new unsupportedoperationexception();        }    }}

  paircollection 对于包含值的实际集合在内部使用泛型。它用第一个参数类型实现了 java.lang.iterable 接口,从而可以直接在新型 for 循环中使用以遍历每对中的第一个值。不幸的是,在使用新型 for 循环时,无法访问实际的迭代器,因而无法获取每一对的第二个值。这就是为什么 清单 1 中的 main() 测试方法使用 while 循环而不是一个新的 for 循环。

  清单 3 给出了包含目录和文件信息的一对类的代码。dirinfo 类使用有类型的 java.util.list 集合表示普通文件和目录的子目录。构造函数将这些集合创建为不可修改的列表,使得它们可以安全地直接返回。fileinfo 类更简单,只包含文件名和最后修改日期。


清单 3. 目录和文件数据类

public class dirinfo{    private final list m_files;    private final list m_directories;    private final date m_lastmodify;        public dirinfo(file dir) {        m_lastmodify = new date(dir.lastmodified());        file[] childs = dir.listfiles();        list files = new arraylist();        list dirs = new arraylist();        for (int i = 0; i < childs.length; i++) {            file child = childs[i];            if (child.isdirectory()) {                dirs.add(new dirinfo(child));            } else if (child.isfile()) {                files.add(new fileinfo(child));            }        }        m_files = collections.unmodifiablelist(files);        m_directories = collections.unmodifiablelist(dirs);    }        public list getdirectories() {        return m_directories;    }    public list getfiles() {        return m_files;    }    public date getlastmodify() {        return m_lastmodify;    }}public class fileinfo{    private final string m_name;    private final date m_lastmodify;        public fileinfo(file file) {        m_name = file.getname();        m_lastmodify = new date(file.lastmodified());    }    public date getlastmodify() {        return m_lastmodify;    }    public string getname() {        return m_name;    }}

  清单 4 给出了 清单 1 中的 main() 方法的运行示例:


清单 4. 示例运行

[dennis]$ java -cp . com.sosnoski.generics.pathdirectory   /home/dennis/bin /home/dennis/xtools /home/dennis/docs/businessdirectory /home/dennis/bin has 31 files and 0 child directoriesdirectory /home/dennis/xtools has 0 files and 3 child directoriesdirectory /home/dennis/docs/business has 34 files and 34 child directories

泛型反射

  泛型是在 java 平台上作为编译时转换实现的。编译器实际上生成与使用非泛型源代码时相同的字节指令,插入运行时类型转换以在每次访问时将值转换为正确的类型。尽管是相同的字节码,但是类型参数信息用 一个新的签名(signature) 属性记录在类模式中。jvm 在装载类时记录这个签名信息,并在运行时通过反射使它可用。在这一节,我将深入挖掘反射 api 如何使类型信息可用的细节。

类型反射接口

  通过反射访问类型参数信息有些复杂。首先,需要有一个具有所提供类型信息的字段(或者其他可提供类型的办法,如方法参数或者返回类型)。然后可以用 java 5 新增的 getgenerictype() 方法从这个字段的 java.lang.reflect.field 实例提取特定于泛型的信息。这个新方法返回一个 java.lang.reflect.type 实例。

  惟一的问题是 type 是一个没有方法的接口。在实例化后,需要检查扩展了 type 的子接口以了解得到的是什么(以及如何使用它)。javadocs 列出了四种子接口,我会依次介绍它们。为了方便,我在清单 5 中给出了接口定义。它们都包括在 java.lang.reflect 包中。


清单 5. type 子接口

interface genericarraytype extends type {    type getgenericcomponenttype();}interface parameterizedtype extends type {    type[] getactualtypearguments();    type getownertype();    type getrawtype();}interface typevariable extends type {    type[] getbounds();    d getgenericdeclaration();    string getname();}interface wildcardtype extends type {    type[] getlowerbounds();    type[] getupperbounds();}

  java.lang.reflect.genericarraytype 是第一个子接口。这个子接口提供了关于数组类型的信息,数组的组件类型可以是参数化的,也可以是一个类型变量。只定义了一个方法 getgenericcomponenttype(),它返回数组组件 type。

  java.lang.reflect.parameterizedtype 是 type 的第二个子接口。它提供了关于具有特定类型参数的泛型类型的信息。这个接口定义了三个方法,其中最让人感兴趣的(对于本文来说)是 getactualtypearguments() 方法。这个方法返回一个 (drum role)数组 . . .还有更多的 type 实例。返回的 type 表示原来(未参数化的)类型的实际类型参数。

  type 的第三个子接口是 java.lang.reflect.typevariable。这个接口给出了表示一个参数类型的变量(如这个类型名中变量 "d")的细节。这个接口定义了三个方法:getbounds(),它返回(您猜) type 实例数组;getgenericdeclaration(),它返回对应于类型变量声明的 java.lang.reflect.genericdeclaration 接口的实例;getname(),它返回类型变量在源代码中使用的名字。这些方法都需要进一步说明。因此我将逐一分析它们。

  由 getbounds() 方法返回的类型数组定义对于变量的类型所施加的限制。这些限制在源代码中作为在模板变量中以 extends b(其中 “b” 是某种类型)的格式添加的子句进行声明。很方便, java.lang.reflect.typevariable 本身就给出了这种形式的上界定义的一个例子 ―― java.lang.reflect.genericdeclaration 是类型参数 “d” 的上界,意味着 “d” 必须是扩展或者实现 genericdeclaration 的类型。

  getgenericdeclaration() 方法提供了一种访问声明了 typevariable 的 genericdeclaration 实例的方式。在标准 java api 中有三个类实现了 genericdeclaration:java.lang.class、java.lang.reflect.constructor 和 java.lang.reflect.method。这三个类是有意义的,因为参数类型只能在类、构造函数和方法中声明。genericdeclaration 接口定义了一个方法,它返回在声明中包含的 typevariable 的数组。

  getname() 方法只是返回与源代码中给出的完全一样的类型变量名。

  java.lang.reflect.wildcardtype 是 type 的第四个(也是最后一个)子接口。wildcardtype 只定义了两个方法,返回通配类型的下界和上界。在前面,我给出了上界的一个例子,下界也类似,但是它们是通过指定一种类型而定义的,提供的类型必须是它的超接口或者超类。

对一个例子的反射

  我在上一节中描述的反射接口提供了解码泛型信息的钩子,但是确定它们有点难度 ―― 不管从哪儿开始,每件事都像是循环并回到 java.lang.reflect.type。为了展示它们是如何工作的,我将利用 清单 1 代码中的一个例子并对它进行反射。

  首先,我尝试访问 清单 1 的 m_pathpairs 字段的类型信息。清单 6 中的代码得到这个字段的泛型类型,检查结果是否为所预期的类型,然后列出原始类型和参数化类型的实际类型参数。在清单 6 的最后以粗体显示了运行这段代码的输出:


清单 6. 第一个反射代码

public static void main(string[] args) throws exception {        // get the basic information    field field =        pathdirectory.class.getdeclaredfield("m_pathpairs");    type gtype = field.getgenerictype();    if (gtype instanceof parameterizedtype) {                // list the raw type information        parameterizedtype ptype = (parameterizedtype)gtype;        type rtype = ptype.getrawtype();        system.out.println("rawtype is instance of " +            rtype.getclass().getname());        system.out.println(" (" + rtype + ")");                // list the actual type arguments        type[] targs = ptype.getactualtypearguments();        system.out.println("actual type arguments are:");        for (int j = 0; j < targs.length; j++) {            system.out.println(" instance of " +                targs[j].getclass().getname() + ":");            system.out.println("  (" + targs[j] + ")");        }    } else {        system.out.println            ("getgenerictype is not a parameterizedtype!");    }}rawtype is instance of java.lang.class (class com.sosnoski.generics.paircollection)actual type arguments are: instance of java.lang.class:  (class java.lang.string) instance of java.lang.class:  (class com.sosnoski.generics.dirinfo)

  到目前为止一切都好。m_pathpairs 字段定义为 paircollection 类型,它匹配反射所访问的类型信息。不过深入实际的参数化类型定义会有些复杂;返回的 type 实例是一个没有实现任何 type 子接口的 java.lang.class 对象。幸运的是,java 5 class 类本身提供了一个深入泛型类定义的细节的方法。这个方法是 gettypeparameters(),它返回一个 typevariable> 数组。在清单 7 中,我修改了 清单 6 的代码以使用这个方法,得到的结果同样以粗体显示在代码中:


清单 7. 深入参数化类型

public static void main(string[] args) throws exception {        // get the basic information    field field =        pathdirectory.class.getdeclaredfield("m_pathpairs");    parameterizedtype ptype =        (parameterizedtype)field.getgenerictype();    class rclas = (class)ptype.getrawtype();    system.out.println("rawtype is class " + rclas.getname());        // list the type variables of the base class    typevariable[] tvars = rclas.gettypeparameters();    for (int i = 0; i < tvars.length; i++) {        typevariable tvar = tvars[i];        system.out.print(" type variable " +            tvar.getname() + " with upper bounds [");        type[] btypes = tvar.getbounds();        for (int j = 0; j < btypes.length; j++) {            if (j > 0) {                system.out.print(" ");            }            system.out.print(btypes[j]);        }        system.out.println("]");    }        // list the actual type arguments    type[] targs = ptype.getactualtypearguments();    system.out.print("actual type arguments are/n (");    for (int j = 0; j < targs.length; j++) {        if (j > 0) {            system.out.print(" ");        }        class tclas = (class)targs[j];        system.out.print(tclas.getname());    }    system.out.print(")");}rawtype is class com.sosnoski.generics.paircollection type variable t with upper bounds [class java.lang.object] type variable u with upper bounds [class java.lang.object]actual type arguments are (java.lang.string com.sosnoski.generics.dirinfo)

  清单 7 的结果显示了解码的结构。实际的类型参数可以由泛型类定义的类型变量匹配。在下一节,我将做此工作作为递推泛型解码方法的一部分。

泛型递推

  在上一节,我快速完成了访问泛型信息的反射方法。现在我将用这些方法构建一个解释泛型的递推处理程序。清单 8 给出了相关的代码:


清单 8. 递推泛型分析

public class reflect{    private static hashset s_processed = new hashset();        private static void describe(string lead, field field) {                // get base and generic types, check kind        class btype = field.gettype();        type gtype = field.getgenerictype();        if (gtype instanceof parameterizedtype) {                        // list basic parameterized type information            parameterizedtype ptype = (parameterizedtype)gtype;            system.out.println(lead + field.getname() +                " is of parameterized type");            system.out.println(lead + ' ' + btype.getname());                        // print list of actual types for parameters            system.out.print(lead + " using types (");            type[] actuals = ptype.getactualtypearguments();            for (int i = 0; i < actuals.length; i++) {                if (i > 0) {                    system.out.print(" ");                }                type actual = actuals[i];                if (actual instanceof class) {                    system.out.print(((class)actual).getname());                } else {                    system.out.print(actuals[i]);                }            }            system.out.println(")");                        // analyze all parameter type classes            for (int i = 0; i < actuals.length; i++) {                type actual = actuals[i];                if (actual instanceof class) {                    analyze(lead, (class)actual);                }            }                    } else if (gtype instanceof genericarraytype) {                        // list array type and use component type            system.out.println(lead + field.getname() +                " is array type " + gtype);            gtype = ((genericarraytype)gtype).                getgenericcomponenttype();                    } else {                        // just list basic information            system.out.println(lead + field.getname() +                " is of type " + btype.getname());        }                // analyze the base type of this field        analyze(lead, btype);    }        private static void analyze(string lead, class clas) {                // substitute component type in case of an array        if (clas.isarray()) {            clas = clas.getcomponenttype();        }                // make sure class should be expanded        string name = clas.getname();        if (!clas.isprimitive() && !clas.isinterface() &&            !name.startswith("java.lang.") &&            !s_processed.contains(name)) {                        // print introduction for class            s_processed.add(name);            system.out.println(lead + "class " +                clas.getname() + " details:");                        // process each field of class            string indent = lead + ' ';            field[] fields = clas.getdeclaredfields();            for (int i = 0; i < fields.length; i++) {                field field = fields[i];                if (!modifier.isstatic(field.getmodifiers())) {                    describe(indent, field);                }            }        }    }        public static void main(string[] args) throws exception {        analyze("", pathdirectory.class);    }}

  清单 8 中的代码使用两个相互递推的方法进行实际的分析。analyze() 方法取一个类作为参数,通过对每个字段的定义进行必要的处理展开这个类。describe() 方法打印特定字段的类型信息的描述,对在这一过程中它遇到的每一个类调用 analyze()。每个方法还有一个给出当前缩进字符串的参数,它使每一级类嵌套都缩进一些空间。

  清单 9 给出了用 清单 8 中的代码分析 清单 1、清单 2 和 清单 3 中代码的完整结构所生成的输出。


清单 9. 泛型示例代码的分析

class com.sosnoski.generics.pathdirectory details: m_pathpairs is of parameterized type  com.sosnoski.generics.paircollection  using types (java.lang.string com.sosnoski.generics.dirinfo) class com.sosnoski.generics.dirinfo details:  m_files is of parameterized type   java.util.list   using types (com.sosnoski.generics.fileinfo)  class com.sosnoski.generics.fileinfo details:   m_name is of type java.lang.string   m_lastmodify is of type java.util.date   class java.util.date details:    fasttime is of type long    cdate is of type sun.util.calendar.basecalendar$date    class sun.util.calendar.basecalendar$date details:     cachedyear is of type int     cachedfixeddatejan1 is of type long     cachedfixeddatenextjan1 is of type long  m_directories is of parameterized type   java.util.list   using types (com.sosnoski.generics.dirinfo)  m_lastmodify is of type java.util.date class com.sosnoski.generics.paircollection details:  m_tvalues is of parameterized type   java.util.arraylist   using types (t)  class java.util.arraylist details:   elementdata is array type e[]   size is of type int  m_uvalues is of parameterized type   java.util.arraylist   using types (u)

  清单 9 的输出给出了泛型类型是如何参数化使用的基本情况,包括为在 dirinfo 类中列出的 m_files 和 m_directories 项指定的类型。但当涉及到 paircollection 类(在底部)时,字段类型只是作为变量给出。对这个字段只显示为变量的原因是由反射提供的泛型类型信息不处理替换 ―― 而是由反射代码的使用者处理泛型类中的替换。这项工作并不太困难,因为可以从清单 9 的输出中进行猜测。这里 m_tvalues 展开的细节显示 arraylist 是用 “t” 类型参数化的,而嵌套的 arraylist 展开显示 elementdata 字段是用类型 “e” 参数化的。要在每一个实例中正确关联这些类型,需要在展开的每一阶段跟踪类型变量实际被替换的类型(如前所述,可用 java.lang.class.gettypeparameters() 方法得到)。在这里,这意味着在 paircollection 展开中的 “t” 和 m_tvaluesarraylist 展开中的 “e” 替换 java.lang.string。我不再给出更多的清单,而是将变化细节留给您。

扫描关注微信公众号