new Instance from Class for generic Type - Java Reflection

Java examples for Reflection:Generic

Description

new Instance from Class for generic Type

Demo Code


//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        System.out.println(newInstance(clazz));
    }// w  w w.  j  av  a 2 s  .com

    public static <T> T newInstance(Class<T> clazz) {
        try {
            return clazz.newInstance();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}

Related Tutorials