Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

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

import java.lang.reflect.InvocationTargetException;

public class Main {

    public static Object xmlToBean(Node beanNode) throws ClassNotFoundException, IllegalAccessException,
            InstantiationException, NoSuchMethodException, InvocationTargetException {
        String className = beanNode.getNodeName();
        System.out.println(className);
        Class clazz = Class.forName(className);
        Object bean = clazz.newInstance();
        NodeList fieldNodeList = beanNode.getChildNodes();
        for (int i = 0; i < fieldNodeList.getLength(); i++) {
            Node fieldNode = fieldNodeList.item(i);
            if (fieldNode.getNodeType() == Node.ELEMENT_NODE) {
                String fieldName = fieldNode.getNodeName();
                if (!fieldName.contains(".")) {
                    String getName = analyzeMethodName(fieldName, "get");
                    String setName = analyzeMethodName(fieldName, "set");
                    System.out.println(setName);
                    clazz.getMethod(setName, clazz.getMethod(getName).getReturnType()).invoke(bean,
                            fieldNode.getTextContent());
                }
            }
        }
        System.out.println(bean);
        return bean;
    }

    private static String analyzeMethodName(String fieldName, String methodType) {
        StringBuilder getName = new StringBuilder(methodType);
        return getName.append(String.valueOf(fieldName.charAt(0)).toUpperCase() + fieldName.substring(1))
                .toString();
    }
}