Java Class New Instance newInstance(Class clz, Class argType, K arg)

Here you can find the source of newInstance(Class clz, Class argType, K arg)

Description

new Instance

License

Open Source License

Declaration

public static <T, K> T newInstance(Class<T> clz, Class<K> argType, K arg) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.lang.reflect.Constructor;

public class Main {
    public static <T, K> T newInstance(Class<T> clz, Class<K> argType, K arg) {
        try {//from   ww w . ja v  a2 s  . c o  m
            Constructor<T> cnstr = clz.getDeclaredConstructor(argType);
            cnstr.setAccessible(true);
            return cnstr.newInstance(arg);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T> T newInstance(Class<T> clz, Object[] args) {
        Class<?>[] argTypes = new Class<?>[args.length];
        for (int i = 0; i < args.length; i++)
            argTypes[i] = args.getClass();
        return newInstance(clz, argTypes, args);
    }

    public static <T> T newInstance(Class<T> clz, Class<?>[] argTypes, Object[] args) {
        try {
            Constructor<T> cnstr = clz.getDeclaredConstructor(argTypes);
            cnstr.setAccessible(true);
            return cnstr.newInstance(args);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static <T, K, V> T newInstance(Class<T> clz, Class<K> arg1Type, Class<V> arg2Type, K arg1, V arg2) {
        try {
            Constructor<T> cnstr = clz.getDeclaredConstructor(arg1Type, arg2Type);
            cnstr.setAccessible(true);
            return cnstr.newInstance(arg1, arg2);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

Related

  1. newInstance(Class clazz, Class[] argumentTypes, Object[] arguments)
  2. newInstance(Class clazz, Class[] parameterTypes, Object[] initargs)
  3. newInstance(Class cls)
  4. newInstance(Class cls)
  5. newInstance(Class cls, Object... args)
  6. newInstance(Class componentType, int size)
  7. newInstance(Class elementType, int len)
  8. newInstance(Class klass)
  9. newInstance(Class klass)