find Constructor With Params - Java Reflection

Java examples for Reflection:Constructor

Description

find Constructor With Params

Demo Code


//package com.java2s;
import java.lang.reflect.Constructor;

public class Main {
    public static void main(String[] argv) throws Exception {
        Class clazz = String.class;
        int paramCount = 2;
        System.out.println(findConstructorWithParams(clazz, paramCount));
    }//from w w  w.j av a 2 s .  com

    private static Constructor findConstructorWithParams(Class clazz,
            int paramCount) throws NoSuchMethodException {
        Constructor[] inits = clazz.getConstructors();
        for (int i = 0; i < inits.length; ++i) {
            if (inits[i].getParameterTypes().length == paramCount) {
                return inits[i];
            }
        }
        throw new NoSuchMethodException("constructor for class '"
                + clazz.getName() + "' with " + paramCount + " parameters");
    }
}

Related Tutorials