java学习:用反射构造bean

先贴一些反射的基本知识:
--------------------------------------------------------------------

一、什么是反射:
反射的概念是由Smith在1982年首次提出的,主要是指程序可以访问、检测和修改它本身状态或行为的一种能力。这一概念的提 出很快引发了计算机科学领域关于应用反射性的研究。它首先被程序语言的设计领域所采用,并在Lisp和面向对象方面取得了成绩。其中 LEAD/LEAD++ 、OpenC++ 、MetaXa和OpenJava等就是基于反射机制的语言。最近,反射机制也被应用到了视窗系统、操作系统和文件系统中。

反射本身并不 是一个新概念,尽管计算机科学赋予了反射概念新的含义。在计算机科学领域,反射是指一类应用,它们能够自描述和自控制。也就是说,这类应用通过采用某种机 制来实现对自己行为的描述(self-representation)和监测(examination),并能根据自身行为的状态和结果,调整或修改应用 所描述行为的状态和相关的语义。

二、什么是Java中的类反射:
Reflection 是 Java 程序开发语言的特征之一,它允许运行中的 Java 程序对自身进行检查,或者说“自审”,并能直接操作程序的内部属性和方法。Java 的这一能力在实际应用中用得不是很多,但是在其它的程序设计语言中根本就不存在这一特性。例如,Pascal、C 或者 C++ 中就没有办法在程序中获得函数定义相关的信息。
Reflection 是 Java 被视为动态(或准动态)语言的关键,允许程序于执行期 Reflection APIs 取得任何已知名称之 class 的內部信息,包括 package、type parameters、superclass、implemented interfaces、inner classes, outer class, fields、constructors、methods、modifiers,並可于执行期生成instances、变更 fields 內容或唤起 methods。

三、Java类反射中所必须的类:
Java的类反射所需要的类并不多,它们分别是:Field、Constructor、Method、Class、Object,下面我将对这些类做一个简单的说明。
Field类:提供有关类或接口的属性的信息,以及对它的动态访问权限。反射的字段可能是一个类(静态)属性或实例属性,简单的理解可以把它看成一个封装反射类的属性的类。
Constructor类:提供关于类的单个构造方法的信息以及对它的访问权限。这个类和Field类不同,Field类封装了反射类的属性,而Constructor类则封装了反射类的构造方法。
Method类:提供关于类或接口上单独某个方法的信息。所反映的方法可能是类方法或实例方法(包括抽象方法)。 这个类不难理解,它是用来封装反射类方法的一个类。
Class类:类的实例表示正在运行的 Java 应用程序中的类和接口。枚举是一种类,注释是一种接口。每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象。
Object类:每个类都使用 Object 作为超类。所有对象(包括数组)都实现这个类的方法。

以上来自 http://www.cnblogs.com/forlina/archive/2011/06/21/2085849.html

--------------------------------------------------------------------

反射的优势在于它可以在程序运行期间动态地构造对象,比较常见的例子是json格式的字符串转化成对象,可以找一些源码参看。

最近写了个方法,用反射的方式根据xml文件和配置文件构造所需的对象,分享在这里。

public static <T> T createObjectFromXMLAndProperty(Document document, Map<String, String> config, Class<T> clazz)

document:xml文件生成的Document对象,数据源

config:配置信息,标明构造的对象所需的数据在xml中的位置

clazz:目标对象

其中的config配置信息是要自己写的,也有一定的写法,例如:

a=xx

b=

c=/root/ele

d=/root/ele[@att]

e=/root/ele;/root/ele[@att]

f=/root/nodes/node[$]

g.aa=/root/nodes/node[$][@key]

g.bb=/root/nodes/node[$][@value]

"="左侧是目标对象中的字段名,右侧是数据/数据的xpath/多个数据

左侧:a:目标对象中的a字段

     g.aa:目标对象中的g,中的aa字段

   同理,对于对象中不是基本类型的对象,用a.b.c....的形式构造

右侧:具体的值

   空:默认值

   xpath:xpath指向的xml中的节点的value

   xpath[@att]:xpath指向的xml中的节点名为“att”的属性

   xpath[$]:取出一系列数据,构造List(仅list可用)

   *;*;...:用";"分割的一系列数据构造目标字段(需要有相应的set方法)

以上的写法可以互相搭配使用。

优点:以后遇到解析xml文件的情况时,只需要编写一个配置文件即可,迭代速度快,之后若有改动也是改配置文件,代码不用变动。

不足:只支持构造可以分解为基本类型和List的对象,还有一些类型待添加,如Map等等;

   当取数逻辑复杂时,无能为力,比如要取出比a节点的value大的所有节点,好好敲代码吧——或者取出来再做处理。

代码如下:

复制代码
public class XMLAnalysisUtils {
    private static final String REGEX_RULE = "\[@(\w+)\]";
    private static final Pattern pat = Pattern.compile(REGEX_RULE);
    private static final Splitter splitter = Splitter.on(";");
    private static Map<Type, AbstractStringConverter> typeMap = Maps.newHashMap();

    /**
     * 根据xml和properties构造对象,properties用于描述对象中的字段的值在xml中到位置
     *
     * @param document xml数据
     * @param config   properties
     * @param clazz    目标对象
     * @return 对象实体
     * @throws Exception
     */
    public static <T> T createObjectFromXMLAndProperty(Document document, Map<String, String> config, Class<T> clazz)
            throws Exception {
        initTypeMap();
        return (T) createObjectFromXMLAndProperty(document, config, clazz, "");
    }

    private static void initTypeMap() {
        typeMap.put(boolean.class, new BooleanConverter());
        typeMap.put(int.class, new IntegerConverter());
        typeMap.put(double.class, new DoubleConverter());
        typeMap.put(Boolean.class, new BooleanConverter());
        typeMap.put(Integer.class, new IntegerConverter());
        typeMap.put(Double.class, new DoubleConverter());
        typeMap.put(String.class, new StringConverter());
    }

    private static Object createObjectFromXMLAndProperty(Document document, Map<String, String> properties, Class clazz, String owner)
            throws Exception {
        Method[] methods = clazz.getDeclaredMethods();
        Object object = clazz.newInstance();

        for (Method method : methods) {
            String methodName = method.getName();
            Type[] type = method.getGenericParameterTypes();

            if (!methodName.startsWith("set")) {
                continue;
            }

            String parameter = owner + methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
            String xPath = properties.get(parameter);

            if (xPath != null) {
                if (xPath.isEmpty()) {
                    if (type.length == 1 && String.class == type[0]) {
                        method.invoke(object, "");
                    }
                    continue;
                }
                if (!isBaseType(type)) {
                    if (type[0] instanceof ParameterizedType) {
                        ParameterizedType pt = (ParameterizedType) type[0];
                        Type tp = pt.getActualTypeArguments()[0];
                        if (!isBaseType(tp)) {
                            continue;
                        }
                        Object results = createList(document, properties, tp, parameter);
                        method.invoke(object, results);
                    }
                    continue;
                }
                List<String> values = getValue(document, xPath);
                if (isAllNull(values)) {
                    continue;
                }
                List<Object> result = transType(values, type);
                if (result == null) {
                    continue;
                }
                method.invoke(object, result.toArray());
                continue;
            }

            if (isBaseType(type)) {
                if (type.length == 1 && String.class == type[0]) {
                    method.invoke(object, "");
                }
                continue;
            }

            if (type[0] instanceof Class) {
                Object res = createObjectFromXMLAndProperty(document, properties, (Class) type[0], parameter + ".");
                method.invoke(object, res);
                continue;
            }

            if (type[0] instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) type[0];
                if (pt.getRawType().equals(List.class)) {
                    Type tp = pt.getActualTypeArguments()[0];
                    Object results = createListObjectFromXMLAndProperty(document, properties, (Class) tp, parameter + ".");
                    method.invoke(object, results);
                }
            }
        }

        return object;
    }

    private static Object createListObjectFromXMLAndProperty(Document document, Map<String, String> properties, Class clazz,
                                                             String owner) throws Exception {
        Method[] methods = clazz.getDeclaredMethods();
        List<Object> objects = Lists.newArrayList();

        Integer row = 1;
        boolean mark = true;
        boolean isList = true;
        while (mark & isList) {
            mark = false;
            isList = false;
            Object object = clazz.newInstance();
            for (Method method : methods) {
                String methodName = method.getName();
                Type[] type = method.getGenericParameterTypes();

                if (!methodName.startsWith("set")) {
                    continue;
                }

                String parameter = owner + methodName.substring(3, 4).toLowerCase() + methodName.substring(4);
                String xPath = properties.get(parameter);

                if (xPath != null) {
                    if (xPath.isEmpty()) {
                        if (type.length == 1 && String.class == type[0]) {
                            method.invoke(object, "");
                        }
                        continue;
                    }
                    if (xPath.contains("$")) {
                        isList = true;
                    }

                    if (!isBaseType(type)) {
                        if (type[0] instanceof ParameterizedType) {
                            ParameterizedType pt = (ParameterizedType) type[0];
                            Type tp = pt.getActualTypeArguments()[0];
                            if (!isBaseType(tp)) {
                                continue;
                            }
                            Object results = createList(document, properties, tp, parameter);
                            method.invoke(object, results);
                        }
                        continue;
                    }
                    List<String> values = getValue(document, xPath.replaceAll("\$", row.toString()));
                    if (isAllNull(values)) {
                        continue;
                    }
                    List<Object> result = transType(values, type);
                    if (result == null) {
                        continue;
                    }
                    mark = mark || xPath.contains("$");//非固定值被invoke时判定为可继续
                    method.invoke(object, result.toArray());
                    continue;
                }

                if (isBaseType(type)) {
                    if (type.length == 1 && String.class == type[0]) {
                        method.invoke(object, "");
                    }
                    continue;
                }

                if (type[0] instanceof Class) {
                    logger.debug("type0:{}, method.name{}", type[0].toString(), method.getName());
                    Object res = createObjectFromXMLAndProperty(document, properties, (Class) type[0], parameter + ".");
                    method.invoke(object, res);
                    continue;
                }

                if (type[0] instanceof ParameterizedType) {
                    ParameterizedType pt = (ParameterizedType) type[0];
                    if (pt.getRawType().equals(List.class)) {
                        Type tp = pt.getActualTypeArguments()[0];
                        Object results = createListObjectFromXMLAndProperty(document, properties, (Class) tp, parameter + ".");
                        method.invoke(object, results);
                    }
                }
            }
            objects.add(object);
            row++;
        }

        objects.remove(objects.size() - 1);
        return objects;
    }

    private static Object createList(Document document, Map<String, String> properties, Type type, String parameter) {
        List<Object> objects = Lists.newArrayList();
        Integer row = 1;
        boolean mark = true;
        boolean isList = true;

        while (mark & isList) {
            mark = false;
            String xPath = properties.get(parameter);
            if (xPath == null) {
                return null;
            }
            if (xPath.isEmpty()) {
                return objects;
            }
            if (!xPath.contains("$")) {
                isList = false;
            }
            xPath = xPath.replaceAll("\$", row.toString());
            List<String> values = getValue(document, xPath);
            if (isAllNull(values)) {
                continue;
            }
            List<Object> result = transType(values, type);
            if (result == null) {
                continue;
            }
            mark = true;
            objects.add(result.get(0));
            row++;
        }

        return objects;
    }

    private static List<Object> transType(List<String> values, Type... types) {
        if (values.size() != types.length) {
            return null;
        }
        List<Object> result = Lists.newArrayList();
        int len = values.size();
        for (int i = 0; i < len; i++) {
            result.add(typeMap.get(types[i]).doForward(values.get(i)));
        }
        return result;
    }

    private static List<String> getValue(Document document, String xPath) {

        List<String> paths = splitter.splitToList(xPath);
        List<String> values = Lists.newArrayList();

        for (String path : paths) {
            if (!path.startsWith("/")) {
                values.add(path);
                continue;
            }

            Element element;
            element = (Element) document.selectSingleNode(path);
            if (element == null) {
                values.add(null);
                continue;
            }
            if (path.contains("@")) {
                Matcher match = pat.matcher(path);
                if (match.find()) {
                    String attr = match.group(1);
                    values.add(element.attributeValue(attr));
                }
                continue;
            }
            values.add(element.getStringValue());
        }

        return values;
    }

    private static boolean isBaseType(Type... types) {
        return typeMap.keySet().containsAll(Lists.newArrayList(types));
    }

    private static boolean isAllNull(List<String> values) {
        boolean result = true;
        if (values == null) {
            return true;
        }
        for (String value : values) {
            result = result && value == null;
        }
        return result;
    }

}
复制代码
原文地址:https://www.cnblogs.com/downey/p/4890800.html