Constructs an object of the passed class name from the passed string. - Java Reflection

Java examples for Reflection:Object

Description

Constructs an object of the passed class name from the passed string.

Demo Code

/**/*from   w w  w. j a v  a  2s . co  m*/
 * Helios, OpenSource Monitoring
 * Brought to you by the Helios Development Group
 *
 * Copyright 2007, Helios Development Group and individual contributors
 * as indicated by the @author tags. See the copyright.txt file in the
 * distribution for a full listing of individual contributors.
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org. 
 *
 */
import java.beans.*;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main{
    public static void main(String[] argv) throws Exception{
        String targetClassName = "java2s.com";
        String value = "java2s.com";
        System.out.println(stringToObject(targetClassName,value));
    }
    /**
     * Constructs an object of the passed class name from the passed string.
     * @param targetClassName The class name of the object to be created.
     * @param value The string to be used to construct the return object.
     * @return The constructed object.
     */
    public static Object stringToObject(String targetClassName, String value) {
        Object object = null;
        String arrayType = null;
        String[] arrayElements = null;
        Object convertedArrayElement = null;
        Object returnArray = null;
        Class<?> arrayClass = null;
        try {
            if (targetClassName.startsWith("[L")
                    && targetClassName.endsWith(";")) {
                arrayType = targetClassName.replace("[L", "");
                arrayType = arrayType.replace(";", "");
                arrayClass = Class.forName(targetClassName, false,
                        BeanHelper.class.getClassLoader())
                        .getComponentType();

                arrayElements = value.split(",");
                returnArray = Array.newInstance(arrayClass,
                        arrayElements.length);
                int index = 0;
                for (String s : arrayElements) {
                    convertedArrayElement = stringToObject(arrayType, s);
                    Array.set(returnArray, index, convertedArrayElement);
                    index++;
                }
                object = returnArray;
            } else if ("java.lang.String".equals(targetClassName)
                    || "java.lang.Object".equals(targetClassName)) {
                object = value;
            } else if ("java.lang.Boolean".equals(targetClassName)
                    || "boolean".equals(targetClassName)) {
                object = Boolean.valueOf(value);
            } else if ("java.lang.Byte".equals(targetClassName)
                    || "byte".equals(targetClassName)) {
                object = new Byte(value);
            } else if ("java.lang.Character".equals(targetClassName)
                    || "char".equals(targetClassName)) {
                object = Character.valueOf(value.charAt(0));
            } else if ("java.lang.Class".equals(targetClassName)) {
                object = Class.forName(value);
            } else if ("java.lang.Double".equals(targetClassName)
                    || "double".equals(targetClassName)) {
                object = new Double(value);
            } else if ("java.lang.Float".equals(targetClassName)
                    || "float".equals(targetClassName)) {
                object = new Float(value);
            } else if ("java.lang.Integer".equals(targetClassName)
                    || "int".equals(targetClassName)) {
                object = new Integer(value);
            } else if ("java.lang.Long".equals(targetClassName)
                    || "long".equals(targetClassName)) {
                object = new Long(value);
            } else {
                throw new Exception("Unsupported Conversion Type["
                        + targetClassName + "]. Please Update "
                        + BeanHelper.class.getName()
                        + ".stringToObject Method");
            }
            return object;
        } catch (Exception e) {
            throw new RuntimeException("Failed to convert value [" + value
                    + "] to an object of type [" + targetClassName + "]", e);
        }

    }
}

Related Tutorials