public static void main(String[] args) { if (args.length < 1) { print(usage); System.exit(0); } int lines = 0; try { Class<?> c = Class.forName(args[0]); Method[] methods = c.getMethods(); Constructor[] ctors = c.getConstructors(); if (args.length == 1) { for (Method method : methods) print(p.matcher(method.toString()).replaceAll("")); for (Constructor ctor : ctors) print(p.matcher(ctor.toString()).replaceAll("")); lines = methods.length + ctors.length; } else { for (Method method : methods) if (method.toString().indexOf(args[1]) != -1) { print(p.matcher(method.toString()).replaceAll("")); lines++; } for (Constructor ctor : ctors) if (ctor.toString().indexOf(args[1]) != -1) { print(p.matcher(ctor.toString()).replaceAll("")); lines++; } } } catch (ClassNotFoundException e) { print("No such class: " + e); } }
public static void main(String[] args) throws Exception { Class clazz = Class.forName("com.mtl.spring.aop.helloworld.ArithmeticCalculatorLoggingProxy"); Object object = clazz.newInstance(); Method[] methods = clazz.getMethods(); StringBuffer sb = new StringBuffer(); sb.append("public class ") .append(object.getClass().getCanonicalName()) .append("{\n") .append("Object object ") .append("\n"); Constructor[] constructors = clazz.getConstructors(); for (Constructor constructor : constructors) { sb.append("\npublic ").append(constructor.getName()).append("("); Class<?> p[] = constructor.getParameterTypes(); for (int j = 0; j < p.length; ++j) { sb.append(p[j].getName() + " arg" + j); if (j < p.length - 1) { sb.delete(sb.length() - 1, sb.length()); } } sb.append(") {").append("\n\n"); sb.append("user.role.cotain(\"/admin/add\") {"); sb.append("\n System.currentTimeMillis();\n"); sb.append("this.object = ").append("arg0"); sb.append("}"); sb.append(" \nSystem.currentTimeMillis();\n"); sb.append("\n}"); } sb.append("\n\n}"); System.out.println(sb); for (Method method : methods) { System.out.println(method.getName()); } }
@SuppressWarnings("unchecked") public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... paramTypes) { Constructor<T>[] ctors = (Constructor<T>[]) type.getConstructors(); for (Constructor<T> ctor : ctors) if (typesMatch(paramTypes, ctor.getParameterTypes())) return ctor; return null; }
/** * すべてのメンバを表示する * * @param Class<?> c メンバを表示したいクラス型オブジェクト */ public static void printAllMembers(Class<?> c) { System.out.println("クラス: "); System.out.println(c); System.out.println("フィールド: "); Field[] declaredfields = c.getDeclaredFields(); Field[] fields = c.getFields(); ArrayList<Field> fieldList = new ArrayList<Field>(fields.length); for (int i = 0; i < fields.length; i++) { fieldList.add(fields[i]); } for (int i = 0; i < declaredfields.length; i++) { if (!fieldList.contains(declaredfields[i])) { fieldList.add(declaredfields[i]); } } Field[] allFields = new Field[fieldList.size()]; for (int i = 0; i < allFields.length; i++) { allFields[i] = fieldList.get(i); } printMembers(allFields); System.out.println("コンストラクタ: "); Constructor[] declaredconstructors = c.getDeclaredConstructors(); Constructor[] constructors = c.getConstructors(); ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length); for (int i = 0; i < constructors.length; i++) { constructorList.add(constructors[i]); } for (int i = 0; i < declaredconstructors.length; i++) { if (!constructorList.contains(declaredconstructors[i])) { constructorList.add(declaredconstructors[i]); } } Constructor[] allConstructors = new Constructor[constructorList.size()]; for (int i = 0; i < allConstructors.length; i++) { allConstructors[i] = constructorList.get(i); } printMembers(allConstructors); System.out.println("メソッド: "); Method[] declaredmethods = c.getDeclaredMethods(); Method[] methods = c.getMethods(); ArrayList<Method> methodList = new ArrayList<Method>(methods.length); for (int i = 0; i < methods.length; i++) { methodList.add(methods[i]); } for (int i = 0; i < declaredmethods.length; i++) { if (!methodList.contains(declaredmethods[i])) { methodList.add(declaredmethods[i]); } } Method[] allMethods = new Method[methodList.size()]; for (int i = 0; i < allMethods.length; i++) { allMethods[i] = methodList.get(i); } printMembers(allMethods); }
/** * Return true if the type is not abstract and not an interface, and has a constructor annotated * with {@link Inject} or its only constructor is the default constructor. * * @param type A class type * @return True if the class type is instantiable */ public static boolean isInstantiable(Class<?> type) { if (!Modifier.isAbstract(type.getModifiers()) && !type.isInterface()) { // first check for a constructor annotated with @Inject, // - this doesn't care how many we'll let the injector complain // if there are more than one for (Constructor<?> c : type.getDeclaredConstructors()) { if (c.getAnnotation(Inject.class) != null) { return true; } } // check if we only have the public default constructor if (type.getConstructors().length == 1 && type.getConstructors()[0].getParameterTypes().length == 0) { return true; } } // no constructor available return false; }
private static boolean testConvexPolygonArch() { boolean pass = true; int test = 1; int cnt; ConvexPolygon poly; Class cl; Class[] temp; System.out.println("ConvexPolygon architecture tests..."); Point a = new Point(7, 7); Point b = new Point(0, 9); Point c = new Point(-3, -5); Point d = new Point(2, -6); Point e = new Point(12, 0); Point[] vertices = new Point[5]; vertices[0] = new Point(a); vertices[1] = new Point(b); vertices[2] = new Point(c); vertices[3] = new Point(d); vertices[4] = new Point(e); poly = new ConvexPolygon(vertices, Color.cyan, false); cl = poly.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 9, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 3, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
@SuppressWarnings("unchecked") private static <T> Constructor<T> getConstructor(Class<T> type) { try { return type.getDeclaredConstructor(); } catch (NoSuchMethodException e) { // Ignore } Constructor[] constructors = type.getConstructors(); if (constructors.length != 1) { throw new IllegalStateException("Class " + type + " should have a single public constructor"); } return constructors[0]; }
@Override public JvmConstructorDefinition resolveConstructorCall( Resolver resolver, List<ActualParam> actualParams) { List<JvmType> argsTypes = new ArrayList<>(); for (ActualParam actualParam : actualParams) { if (actualParam.isNamed()) { throw new SemanticErrorException( actualParam, "It is not possible to use named parameters on Java classes"); } else { argsTypes.add(actualParam.getValue().calcType(resolver).jvmType(resolver)); } } return ReflectionBasedMethodResolution.findConstructorAmong( argsTypes, resolver, Arrays.asList(clazz.getConstructors()), this); }
/** * Finds the constructor of the given class that is compatible with the given arguments. * * @param type the class to find the constructor of * @param args the arguments * @return the constructor */ public static Constructor findConstructor(Class<?> type, Object[] args) { outer: for (Constructor constructor : type.getConstructors()) { Class<?>[] paramTypes = constructor.getParameterTypes(); if (paramTypes.length != args.length) continue; for (int i = 0; i < args.length; i++) { Object arg = args[i]; if (arg != null && !paramTypes[i].isAssignableFrom(arg.getClass())) continue outer; if (arg == null && paramTypes[i].isPrimitive()) continue outer; } return constructor; } throw new GrammarException( "No constructor found for %s and the given %s arguments", type, args.length); }
public static void main(String[] args) throws Exception { Class<ClassTest> clazz = ClassTest.class; System.out.println("============================================="); Constructor[] ctors = clazz.getDeclaredConstructors(); System.out.println("classTest的全部构造器如下:"); for (Constructor c : ctors) { System.out.println(c); } System.out.println("============================================="); Constructor[] publicCtors = clazz.getConstructors(); System.out.println("ClassTest的全部public构造器如下:"); for (Constructor c : publicCtors) { System.out.println(c); } System.out.println("============================================="); Method[] mtds = clazz.getMethods(); System.out.println("ClassTest的全部public方法如下:"); for (Method md : mtds) { System.out.println(md); } System.out.println("============================================="); System.out.println("ClassTest带一个字符串参数的info方法为:" + clazz.getMethod("info", String.class)); Annotation[] ans = clazz.getAnnotations(); System.out.println("ClassTest的全部annotation为:"); for (Annotation an : ans) { System.out.println(an); } System.out.println("该元素上的@SuppressWarnings注释为:" + clazz.getAnnotation(SuppressWarnings.class)); System.out.println("============================================="); Class<?>[] inners = clazz.getDeclaredClasses(); System.out.println("ClassTest的全部内部类如下:"); for (Class c : inners) { System.out.println(c); } System.out.println("============================================="); Class inClazz = Class.forName("ClassTest$Inner"); System.out.println("inClazz对应的外部类为:" + inClazz.getDeclaringClass()); System.out.println("ClassTest的包为:" + clazz.getPackage()); System.out.println("ClassTest的父类:" + clazz.getSuperclass()); }
public void checkNoArgueMentConstructor(Class klass) { Constructor[] constructor = klass.getConstructors(); boolean noArguement = false; for (int j = 0; j < constructor.length; j++) { Class<?>[] cklass = constructor[j].getParameterTypes(); String length = "" + cklass.length; if (!length.isEmpty()) { noArguement = true; } } if (noArguement == true) { textArea4.setText("this class does have a no arguement constructor."); } else { textArea4.setText("this class does not have a no arguement constructor."); } }
private static Object createArgumentPlaceholderForUnknownClass( Class<?> clazz, Integer placeholderId) throws IllegalAccessException, InstantiationException { FinalClassArgumentCreator<?> creator = FINAL_CLASS_ARGUMENT_CREATORS.get(clazz); if (creator != null) return creator.createArgumentPlaceHolder(placeholderId); for (Constructor constructor : clazz.getConstructors()) { Class<?>[] params = constructor.getParameterTypes(); if (params.length != 1) continue; try { if (params[0] == String.class) return constructor.newInstance(String.valueOf(placeholderId)); if (isNumericClass(params[0])) return constructor.newInstance(placeholderId); } catch (IllegalAccessException e1) { } catch (InvocationTargetException e2) { } } return clazz.newInstance(); }
private static boolean testTriangleArch() { boolean pass = true; int test = 1; int cnt; Triangle tri; Class cl; Class[] temp; System.out.println("Triangle architecture tests..."); Point a = new Point(0, 0); Point b = new Point(3, 0); Point c = new Point(0, 4); tri = new Triangle(a, b, c, Color.cyan, false); cl = tri.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 13, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 5, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
public ConstructorArgumentConverter(Class<T> clazz, Object... arguments) { for (Constructor<?> c : clazz.getConstructors()) { if (isCompatible(c, arguments)) { this.constructor = (Constructor<T>) c; break; } } if (constructor == null) throw new IntrospectionException( "Unable to find a constructor of " + clazz.getName() + " compatible with the given arguments"); if (arguments != null) for (Object argument : arguments) { argumentConverters.add(new ArgumentConverter<F, Object>(argument)); } }
public static void printConstructors(Class<?> c) { display2.append("コンストラクタ\r\n"); Constructor[] declaredconstructors = c.getDeclaredConstructors(); Constructor[] constructors = c.getConstructors(); ArrayList<Constructor> constructorList = new ArrayList<Constructor>(constructors.length); for (int i = 0; i < constructors.length; i++) { constructorList.add(constructors[i]); } for (int i = 0; i < declaredconstructors.length; i++) { if (!constructorList.contains(declaredconstructors[i])) { constructorList.add(declaredconstructors[i]); } } Constructor[] allConstructors = new Constructor[constructorList.size()]; for (int i = 0; i < allConstructors.length; i++) { allConstructors[i] = constructorList.get(i); } printMembers(allConstructors); }
private static boolean testCircleArch() { boolean pass = true; int test = 1; int cnt; Circle circle; Class cl; Class[] temp; System.out.println("Circle architecture tests..."); circle = new Circle(5.6789, new Point(-99, 66), Color.cyan, false); cl = circle.getClass(); pass &= test(cl.getConstructors().length == 1, test++); pass &= test((temp = cl.getInterfaces()).length == 1, test++); pass &= test(temp[0].getName().equals("Shape"), test++); pass &= test(verifyEqualsMethodSignature(cl), test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 10, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 4, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
public static void printConstructors(AClass aClass) { Class c = aClass.getClass(); // 获取指定类的类名 String className = c.getName(); try { // 获取指定类的构造方法 Constructor[] theConstructors = c.getConstructors(); for (int i = 0; i < theConstructors.length; i++) { // 获取指定构造方法的参数的集合 Class[] parameterTypes = theConstructors[i].getParameterTypes(); System.out.print(className + "("); for (int j = 0; j < parameterTypes.length; j++) System.out.print(parameterTypes[j].getName() + " "); System.out.println(")"); } } catch (Exception e) { e.printStackTrace(); } }
private static boolean testCanvasArch() { boolean pass = true; int test = 1; int cnt; Canvas canvas; Class cl; Class[] temp; System.out.println("Canvas architecture tests..."); canvas = new Canvas(); cl = canvas.getClass(); pass &= test(cl.getConstructors().length == 1, test++); cnt = countModifiers(cl.getDeclaredMethods(), Modifier.PUBLIC); pass &= test(cnt == 10, test++); cnt = cl.getFields().length; pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED); pass &= test(cnt == 0, test++); cnt = countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE); pass &= test(cnt == 1, test++); // Count and test number of of PACKAGE fields cnt = cl.getDeclaredFields().length - countModifiers(cl.getDeclaredFields(), Modifier.PRIVATE) - countModifiers(cl.getDeclaredFields(), Modifier.PROTECTED) - countModifiers(cl.getDeclaredFields(), Modifier.PUBLIC); pass &= test(cnt == 0, test++); return pass; }
/** Reflect operations demo */ public static void reflect(Object obj) { // `cls用于描述对象所属的类` Class cls = obj.getClass(); print("Class Name: " + cls.getCanonicalName()); // `fields包含对象的所有属性` Field[] fields = cls.getDeclaredFields(); print("List of fields:"); for (Field f : fields) { print(String.format("%30s %15s", f.getType(), f.getName())); } // `methods包含对象的所有方法` Method[] methods = cls.getDeclaredMethods(); print("List of methods:"); for (Method m : methods) print( String.format( "%30s %15s %30s", m.getReturnType(), m.getName(), Arrays.toString(m.getParameterTypes()))); Constructor[] constructors = cls.getConstructors(); print("List of contructors:"); for (Constructor c : constructors) print(String.format("%30s %15s", c.getName(), Arrays.toString(c.getParameterTypes()))); }
public static byte[] createAdapterCode( ObjToIntMap functionNames, String adapterName, Class<?> superClass, Class<?>[] interfaces, String scriptClassName) { ClassFileWriter cfw = new ClassFileWriter(adapterName, superClass.getName(), "<adapter>"); cfw.addField( "factory", "Laurora/javascript/ContextFactory;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "delegee", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); cfw.addField( "self", "Laurora/javascript/Scriptable;", (short) (ClassFileWriter.ACC_PUBLIC | ClassFileWriter.ACC_FINAL)); int interfacesCount = interfaces == null ? 0 : interfaces.length; for (int i = 0; i < interfacesCount; i++) { if (interfaces[i] != null) cfw.addInterface(interfaces[i].getName()); } String superName = superClass.getName().replace('.', '/'); Constructor<?>[] ctors = superClass.getConstructors(); for (Constructor<?> ctor : ctors) { generateCtor(cfw, adapterName, superName, ctor); } generateSerialCtor(cfw, adapterName, superName); if (scriptClassName != null) { generateEmptyCtor(cfw, adapterName, superName, scriptClassName); } ObjToIntMap generatedOverrides = new ObjToIntMap(); ObjToIntMap generatedMethods = new ObjToIntMap(); // generate methods to satisfy all specified interfaces. for (int i = 0; i < interfacesCount; i++) { Method[] methods = interfaces[i].getMethods(); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); if (Modifier.isStatic(mods) || Modifier.isFinal(mods)) { continue; } String methodName = method.getName(); Class<?>[] argTypes = method.getParameterTypes(); if (!functionNames.has(methodName)) { try { superClass.getMethod(methodName, argTypes); // The class we're extending implements this method and // the JavaScript object doesn't have an override. See // bug 61226. continue; } catch (NoSuchMethodException e) { // Not implemented by superclass; fall through } } // make sure to generate only one instance of a particular // method/signature. String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); } } } // Now, go through the superclass's methods, checking for abstract // methods or additional methods to override. // generate any additional overrides that the object might contain. Method[] methods = getOverridableMethods(superClass); for (int j = 0; j < methods.length; j++) { Method method = methods[j]; int mods = method.getModifiers(); // if a method is marked abstract, must implement it or the // resulting class won't be instantiable. otherwise, if the object // has a property of the same name, then an override is intended. boolean isAbstractMethod = Modifier.isAbstract(mods); String methodName = method.getName(); if (isAbstractMethod || functionNames.has(methodName)) { // make sure to generate only one instance of a particular // method/signature. Class<?>[] argTypes = method.getParameterTypes(); String methodSignature = getMethodSignature(method, argTypes); String methodKey = methodName + methodSignature; if (!generatedOverrides.has(methodKey)) { generateMethod(cfw, adapterName, methodName, argTypes, method.getReturnType(), true); generatedOverrides.put(methodKey, 0); generatedMethods.put(methodName, 0); // if a method was overridden, generate a "super$method" // which lets the delegate call the superclass' version. if (!isAbstractMethod) { generateSuper( cfw, adapterName, superName, methodName, methodSignature, argTypes, method.getReturnType()); } } } } // Generate Java methods for remaining properties that are not // overrides. ObjToIntMap.Iterator iter = new ObjToIntMap.Iterator(functionNames); for (iter.start(); !iter.done(); iter.next()) { String functionName = (String) iter.getKey(); if (generatedMethods.has(functionName)) continue; int length = iter.getValue(); Class<?>[] parms = new Class[length]; for (int k = 0; k < length; k++) parms[k] = ScriptRuntime.ObjectClass; generateMethod(cfw, adapterName, functionName, parms, ScriptRuntime.ObjectClass, false); } return cfw.toByteArray(); }
public static void main(String[] args) { // Obtain the class object if we know the name of the class Class rental = RentCar.class; try { // get the absolute name of the class String rentalClassPackage = rental.getName(); System.out.println("Class Name is: " + rentalClassPackage); // get the simple name of the class (without package info) String rentalClassNoPackage = rental.getSimpleName(); System.out.println("Class Name without package is: " + rentalClassNoPackage); // get the package name of the class Package rentalPackage = rental.getPackage(); System.out.println("Package Name is: " + rentalPackage); // get all the constructors of the class Constructor[] constructors = rental.getConstructors(); System.out.println("Constructors are: " + Arrays.toString(constructors)); // get constructor with specific argument Constructor constructor = rental.getConstructor(Integer.TYPE); // initializing an object of the RentCar class RentCar rent = (RentCar) constructor.newInstance(455); // get all methods of the class including declared methods of // superclasses // in that case, superclass of RentCar is the class java.lang.Object Method[] allmethods = rental.getMethods(); System.out.println("Methods are: " + Arrays.toString(allmethods)); for (Method method : allmethods) { System.out.println("method = " + method.getName()); } // get all methods declared in the class // but excludes inherited methods. Method[] declaredMethods = rental.getDeclaredMethods(); System.out.println("Declared Methods are: " + Arrays.toString(declaredMethods)); for (Method dmethod : declaredMethods) { System.out.println("method = " + dmethod.getName()); } // get method with specific name and parameters Method oneMethod = rental.getMethod("computeRentalCost", new Class[] {Integer.TYPE}); System.out.println("Method is: " + oneMethod); // call computeRentalCost method with parameter int oneMethod.invoke(rent, 4); // get all the parameters of computeRentalCost Class[] parameterTypes = oneMethod.getParameterTypes(); System.out.println( "Parameter types of computeRentalCost() are: " + Arrays.toString(parameterTypes)); // get the return type of computeRentalCost Class returnType = oneMethod.getReturnType(); System.out.println("Return type is: " + returnType); // gets all the public member fields of the class RentCar Field[] fields = rental.getFields(); System.out.println("Public Fields are: "); for (Field oneField : fields) { // get public field name Field field = rental.getField(oneField.getName()); String fieldname = field.getName(); System.out.println("Fieldname is: " + fieldname); // get public field type Object fieldType = field.getType(); System.out.println("Type of field " + fieldname + " is: " + fieldType); // get public field value Object value = field.get(rent); System.out.println("Value of field " + fieldname + " is: " + value); } // How to access private member fields of the class // getDeclaredField() returns the private field Field privateField = RentCar.class.getDeclaredField("type"); String name = privateField.getName(); System.out.println("One private Fieldname is: " + name); // makes this private field instance accessible // for reflection use only, not normal code privateField.setAccessible(true); // get the value of this private field String fieldValue = (String) privateField.get(rent); System.out.println("fieldValue = " + fieldValue); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } }
@SuppressWarnings({"unchecked", "rawtypes"}) public static <T> T newInstance(Class<T> type, boolean strict, Object... parameters) { if (parameters.length == 0) return newInstanceFromDefaultConstructor(type); Constructor<T> constructorToUse = null; try { Constructor<T>[] constructors = (Constructor<T>[]) type.getConstructors(); List<Constructor<T>> candidates = new ArrayList<Constructor<T>>(constructors.length); int paramCount = parameters.length; for (Constructor<T> constructor : constructors) if (constructor.getParameterTypes().length == paramCount) candidates.add(constructor); if (candidates.size() == 1) constructorToUse = candidates.get(0); else if (candidates.size() == 0) throw new ConfigurationError( "No constructor with " + paramCount + " parameters found for " + type); else { // there are several candidates - find the first one with matching types Class<?>[] paramTypes = new Class[parameters.length]; for (int i = 0; i < parameters.length; i++) paramTypes[i] = parameters[i].getClass(); for (Constructor c : type.getConstructors()) { if (typesMatch(c.getParameterTypes(), paramTypes)) { constructorToUse = c; break; } } // there is no ideal match if (constructorToUse == null) { if (strict) throw new NoSuchMethodException( "No appropriate constructor found: " + type + '(' + ArrayFormat.format(", ", paramTypes) + ')'); Exception mostRecentException = null; for (Constructor<T> candidate : candidates) { try { return newInstance(candidate, strict, parameters); } catch (Exception e) { mostRecentException = e; logger.warn("Exception in constructor call: " + candidate, e); continue; // ignore exception and try next constructor } } // no constructor could be called without exception String errMsg = (mostRecentException != null ? "None of these constructors could be called without exception: " + candidates + ", latest exception: " + mostRecentException : type + " has no appropriate constructor for the arguments " + ArrayFormat.format(", ", parameters)); throw new ConfigurationError(errMsg); } } if (!strict) parameters = convertArray(parameters, constructorToUse.getParameterTypes()); return newInstance(constructorToUse, parameters); } catch (SecurityException e) { throw ExceptionMapper.configurationException(e, constructorToUse); } catch (NoSuchMethodException e) { throw ExceptionMapper.configurationException(e, type); } }