集册 Java实例教程 实例化一个类而不会引发异常

实例化一个类而不会引发异常

欢马劈雪     最近更新时间:2020-01-02 10:19:05

523
实例化一个类而不会引发异常


import java.lang.reflect.InvocationTargetException;

import java.lang.reflect.Method;/*时代Java - nowjava.com*/


public class Main{

    public static void main(String[] argv) throws Exception{

        Class clazz = String.class;

        System.out.println(instantiateClass(clazz));

    }

    /**

     * instantiate a class without throwing a exception

     * 

     * @param <T>

     * @param clazz

     * @return

     * @throws WrappedRuntimeException

     */

    public static <T> T instantiateClass(final Class<T> clazz)

            throws WrappedRuntimeException {

        try {

            T result = clazz.newInstance();

            return result;

        } catch (Exception e) {

            throw new WrappedRuntimeException(e);

        }


    }/** 时代Java 提 供 **/

    @SuppressWarnings("unchecked")

    public static <T> T instantiateClass(final String clazzName)

            throws WrappedRuntimeException {


        Class<T> clazz;

        try {

            clazz = (
展开阅读全文