Java Class New Instance newInstance(String cls, Class interfaceType)

Here you can find the source of newInstance(String cls, Class interfaceType)

Description

new Instance

License

Open Source License

Declaration

public static <T> T newInstance(String cls, Class<T> interfaceType) 

Method Source Code

//package com.java2s;

public class Main {
    public static <T> T newInstance(String cls, Class<T> interfaceType) {
        Class<?> clazz;//  w  ww .  ja va 2s  .c o  m
        try {
            clazz = Class.forName(cls);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("class not found: " + cls, e);
        }
        Object obj;
        try {
            obj = clazz.newInstance();
        } catch (InstantiationException e) {
            throw new IllegalArgumentException("cannot instantiate class: " + cls, e);
        } catch (IllegalAccessException e) {
            throw new IllegalArgumentException("cannot access no-args constructor of class: " + cls, e);
        }
        T t;
        try {
            t = interfaceType.cast(obj);
        } catch (ClassCastException e) {
            throw new IllegalArgumentException(
                    "cannot cast new instance of " + cls + " to interface type " + interfaceType.getName());
        }

        return t;
    }

    private static int cast(byte b) {
        if (b >= 0) {
            return b;
        }
        return 256 + b;
    }
}

Related

  1. newInstance(String className, Object[] args)
  2. newInstance(String className, Object[] args)
  3. newInstance(String classname, Properties properties)
  4. newInstance(String clazz)
  5. newInstance(String clazzStr)
  6. newInstance(String klass)
  7. newInstance(String name)
  8. newInstance(String name, ClassLoader loader)
  9. newInstance(String s)