Java Class New Instance newInstance(Type type)

Here you can find the source of newInstance(Type type)

Description

new Instance

License

Apache License

Declaration

public static Object newInstance(Type type)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.lang.reflect.Type;

public class Main {
    private static final String TYPE_CLASS_NAME_PREFIX = "class ";
    private static final String TYPE_INTERFACE_NAME_PREFIX = "interface ";

    public static Object newInstance(Type type)
            throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        Class<?> clazz = getClass(type);
        if (clazz == null) {
            return null;
        }/*from w w  w.java  2 s . c  om*/
        return clazz.newInstance();
    }

    public static Class<?> getClass(Type type) throws ClassNotFoundException {
        String className = getClassName(type);
        if (className == null || className.isEmpty()) {
            return null;
        }
        return Class.forName(className);
    }

    public static String getClassName(Type type) {
        if (type == null) {
            return "";
        }
        String className = type.toString();
        if (className.startsWith(TYPE_CLASS_NAME_PREFIX)) {
            className = className.substring(TYPE_CLASS_NAME_PREFIX.length());
        } else if (className.startsWith(TYPE_INTERFACE_NAME_PREFIX)) {
            className = className.substring(TYPE_INTERFACE_NAME_PREFIX.length());
        }
        return className;
    }
}

Related

  1. newInstance(String type, Class cast)
  2. newInstance(T obj)
  3. newInstance(T obj, Class argType, Object arg)
  4. newInstance(Type type)
  5. newInstance(Type type)
  6. newInstanceByName(String className)
  7. newInstanceByName(String className)
  8. newInstanceForClass(Class type)
  9. newInstanceForName(String fullClassName, Object... args)