Java Reflection Constructor Get getConstructor(Class clazz, Class... args)

Here you can find the source of getConstructor(Class clazz, Class... args)

Description

Gets a constructor that has the specified types of arguments.

License

Open Source License

Declaration

public static MethodHandle getConstructor(Class<?> clazz, Class<?>... args) 

Method Source Code

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

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.reflect.Constructor;

import java.util.Arrays;

public class Main {
    /**//from  w  w w .java 2  s . c  o  m
     * Gets a constructor that has the specified types of arguments.
     * Throw an IllegalStateException if the class does not have such a constructor.
     */
    public static MethodHandle getConstructor(Class<?> clazz, Class<?>... args) {
        try {
            // We use unreflect so that we can make the constructor accessible
            Constructor<?> ctor = clazz.getDeclaredConstructor(args);
            ctor.setAccessible(true);
            return MethodHandles.lookup().unreflectConstructor(ctor);
        } catch (NoSuchMethodException e) {
            throw new IllegalStateException(
                    clazz.getName() + " has no constructor with args " + Arrays.toString(args), e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(
                    "Problem getting constructor for " + clazz.getName() + " with args " + Arrays.toString(args),
                    e);
        }
    }
}

Related

  1. getConstructor(Class clz, Class expectedTypes[])
  2. getConstructor(Class type, Class[] argTypes)
  3. getConstructor(Class c, Class[] args)
  4. getConstructor(Class clazz, boolean declared, Class... args)
  5. getConstructor(Class clazz, Class... args)
  6. getConstructor(Class clazz, Class... parameterTypes)
  7. getConstructor(Class clazz, Class... parameterTypes)
  8. getConstructor(Class clazz, Class... params)
  9. getConstructor(Class clazz, Class... params)