Here you can find the source of getConstructorWithArgs(Class
Parameter | Description |
---|---|
clazz | - class to look for the constructor in |
args | - arguments that the constructor should have |
public static <e extends Object> Constructor<e> getConstructorWithArgs(Class<e> clazz, Object... args)
//package com.java2s; //License from project: Open Source License import java.lang.reflect.Constructor; public class Main { /**/* w w w . ja v a2 s. com*/ * Looks for a constructor matching the argument given. * * @param clazz - class to look for the constructor in * @param args - arguments that the constructor should have * @return first match found */ public static <e extends Object> Constructor<e> getConstructorWithArgs(Class<e> clazz, Object... args) { if (clazz != null) { Constructor<?>[] constructors = clazz.getConstructors(); for (Constructor<?> constructor : constructors) { if (constructor.getParameterTypes().length == args.length) { Class<?>[] pType = constructor.getParameterTypes(); for (int i = 0; i < pType.length; i++) { if (!pType[i].equals(args[i].getClass())) { continue; } if (i == pType.length - 1) { try { Constructor<e> con = (Constructor<e>) constructor; return con; } catch (ClassCastException e) { } } } } } } return null; } }