Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

import org.w3c.dom.DOMException;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class Main {
    public static <T> T loadBean(Node node, Class<T> beanClass)
            throws IntrospectionException, InstantiationException, IllegalAccessException, IllegalArgumentException,
            DOMException, InvocationTargetException {
        T store = beanClass.newInstance();

        Map<String, PropertyDescriptor> properties = new HashMap<String, PropertyDescriptor>();
        BeanInfo beanInfo = Introspector.getBeanInfo(beanClass);
        for (PropertyDescriptor property : beanInfo.getPropertyDescriptors()) {
            properties.put(property.getName(), property);
        }

        NamedNodeMap attributes = node.getAttributes();
        for (int i = 0; i < attributes.getLength(); i++) {
            Node attribute = attributes.item(i);
            PropertyDescriptor property = properties.get(attribute.getNodeName());
            if (property != null && property.getPropertyType().equals(String.class)
                    && property.getWriteMethod() != null) {
                property.getWriteMethod().invoke(store, attribute.getNodeValue());
            }
        }

        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node child = childNodes.item(i);
            PropertyDescriptor property = properties.get(child.getNodeName());
            if (property != null && property.getPropertyType().equals(String.class)
                    && property.getWriteMethod() != null) {
                property.getWriteMethod().invoke(store, child.getTextContent());
            }
        }

        return store;
    }
}