Java Class New Instance newInstanceFromUnknownArgumentTypes(Class cls, Object[] args)

Here you can find the source of newInstanceFromUnknownArgumentTypes(Class cls, Object[] args)

Description

new Instance From Unknown Argument Types

License

Apache License

Declaration

public static <T> T newInstanceFromUnknownArgumentTypes(Class<T> cls, Object[] args) 

Method Source Code


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

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import java.util.Arrays;

import java.util.stream.Collectors;

public class Main {
    public static <T> T newInstanceFromUnknownArgumentTypes(Class<T> cls, Object[] args) {
        try {// ww w  .  j a  va 2s.c  om
            return cls.getDeclaredConstructor(getArgumentTypesFromArgumentList(args)).newInstance(args);
        } catch (InstantiationException | InvocationTargetException | IllegalAccessException ie) {
            throw new RuntimeException(ie);
        } catch (NoSuchMethodException nsme) {
            // Now we need to find a matching primitive type.
            // We can maybe cheat by running through all the constructors until we get what we want
            // due to autoboxing
            Constructor[] ctors = Arrays.stream(cls.getDeclaredConstructors())
                    .filter(c -> c.getParameterTypes().length == args.length).toArray(Constructor[]::new);
            for (Constructor<?> ctor : ctors) {
                try {
                    return (T) ctor.newInstance(args);
                } catch (Exception e) {
                    // silently drop exceptions since we are brute forcing here...
                }
            }

            String argTypes = Arrays.stream(args).map(Object::getClass).map(Object::toString)
                    .collect(Collectors.joining(", "));

            String availableCtors = Arrays.stream(ctors).map(Constructor::toString)
                    .collect(Collectors.joining(", "));

            throw new RuntimeException(
                    "Couldn't find a matching ctor for " + argTypes + "; available ctors are " + availableCtors);
        }
    }

    /**
     * Extract argument types from a string that represents the method
     * signature.
     * @param args Signature string
     * @return Array of types
     */
    public static Class[] getArgumentTypesFromArgumentList(Object[] args) {
        return Arrays.stream(args).map(Object::getClass).toArray(Class[]::new);
    }
}

Related

  1. newInstanceByName(String className)
  2. newInstanceForClass(Class type)
  3. newInstanceForName(String fullClassName, Object... args)
  4. newInstanceFromClass(final Class clazz)
  5. newInstanceFromClassName(String className, Class classType)
  6. newInstanceHard(String name)
  7. newInstanceOf(Class clazz)
  8. newInstanceOf(String className)
  9. newInstanceOrThrow(final Class clazz)