Class for Name - Java Reflection

Java examples for Reflection:Class

Description

Class for Name

Demo Code


//package com.java2s;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import java.util.Map;

public class Main {


    public static final String ARRAY_SUFFIX = "[]";

    private static Map primitiveClassNameMap;

    private static Map primitiveClassWrapperMap;

    public static Class forName(String className)
            throws ClassNotFoundException {
        return forName(className, Thread.currentThread()
                .getContextClassLoader());
    }//from www.  j av  a  2s .  co  m

    public static Class forName(String className, ClassLoader classLoader)
            throws ClassNotFoundException {
        Class result = (Class) primitiveClassNameMap.get(className);
        if (null != result) {
            return result;
        }

        if (className.endsWith(ARRAY_SUFFIX)) {
            // special handling for array class names
            String elementClassName = className.substring(0,
                    className.length() - ARRAY_SUFFIX.length());
            Class elementClass = forName(elementClassName, classLoader);
            return Array.newInstance(elementClass, 0).getClass();
        } else {
            return Class.forName(className, true, classLoader);
        }
    }

    public static Object newInstance(Class theClass)
            throws InstantiationException, IllegalAccessException {
        if (null != primitiveClassWrapperMap.get(theClass)) {
            theClass = (Class) primitiveClassWrapperMap.get(theClass);
        }
        return theClass.newInstance();
    }

    public static Object newInstance(Class theClass, String param)
            throws InstantiationException, IllegalAccessException,
            SecurityException, NoSuchMethodException,
            IllegalArgumentException, InvocationTargetException {
        if (null != primitiveClassWrapperMap.get(theClass)) {
            theClass = (Class) primitiveClassWrapperMap.get(theClass);
        }
        Constructor constructor = theClass
                .getConstructor(new Class[] { java.lang.String.class });
        return constructor.newInstance(new Object[] { param });
    }
}

Related Tutorials