Class new Instance - Java Reflection

Java examples for Reflection:Class Loader

Description

Class new Instance

Demo Code


//package com.java2s;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class theClass = String.class;
        System.out.println(newInstance(theClass));
    }//from   www .  j ava  2 s. c  om

    private static Map primitiveClassWrapperMap;

    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