提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
找到一个参数构造函数,该参数可从参数类分配
//package com.nowjava; /** 来自 时 代 Java - nowjava.com**/ import java.lang.reflect.Constructor; public class Main { public static void main(String[] argv) throws Exception { Class clazz = String.class; Class parameter = String.class; System.out.println(findConstructor(clazz, parameter)); } /** * Find one parameter constructor which parameter is * assignable from parameter class * * @param clazz class whose constructor we are finding * @param parameter parameter class * @return constructor */ public static <T> Constructor<T> findConstructor(Class<T> clazz, Class parameter) { Constructor[] constructors = clazz.getDeclaredConstructors(); for (Constructor constructor : constructors) { if (constructor.getParameterTypes().length == 1 && constructor.getParameterTypes()[0] .isAssignableFrom(parameter)) /** n o w j a v a . c o m 提供 **/ return constructor; } return null; } /** * Find constructor of class which has these parameters * * @param clazz class of constructor we are finding * @param parameters constructor parameters * @param <T> type of class * @return constructor or null if cannot be find */ public static <T> Constructor<T> findConstructor(Class<T> clazz, Class[] parameters) { Constructor[] constructors = clazz.getConstructors(); for (Constructor constructor : constructors) { if (constructor.getParameterTypes().length == parameters.length) { if (isAssignable(constructor.getParameterTypes(), parameters)) return constructor; } } return null; } /** * Determine if classes can be assigned from * * @param c1 first array of classes * @param c2 second array of classes * @return true if c1 array can be assigned from c2 array */ public static boolean isAssignable(