/** * Returns the correct implementation instance for the interface <code>type</code>. For convention * the implentation is named <code>InterfaceName + Impl</code>. * * @param type The interface type * @return The correct ModelProxy subclass (if exists), a ModelProxy instance otherwise * @throws MalformedModelException is the interface or the implementation are not well formed * (they don't respect the conventions). * @throws ModelRuntimeException is any error occurs during the instantiation */ protected ModelProxy createInstance(Class type) { Class backClass; if (implementations.containsKey(type)) backClass = implementations.get(type); else { /* type never seen */ try { Package pkg = type.getPackage(); String pkgN = pkg == null ? "" : pkg.getName(); backClass = Class.forName(pkgN + tableName(type) + CommonStatic.getImplementationSuffix()); } catch (Exception e) { backClass = ModelProxy.class; } Validator.validateModel(type, backClass); initFieldsTypes(type); implementations.put(type, backClass); } ModelProxy impl = null; try { impl = (ModelProxy) backClass.newInstance(); } catch (Exception e) { throw new ModelRuntimeException(e.getMessage()); } return impl; }
// // Find all the java.sql interfaces implemented by a class and find // the methods in those interfaces which raise // SQLFeatureNotSupportedException when called on the passed-in candidate object. // private void vetInterfaces( Object candidate, Class myClass, HashSet<String> unsupportedList, HashSet<String> notUnderstoodList) throws Exception { Class superClass = myClass.getSuperclass(); if (superClass != null) { vetInterfaces(candidate, superClass, unsupportedList, notUnderstoodList); } // // The contract for Class.getInterfaces() states that the interfaces // come back in a deterministic order, namely, in the order that // they were declared in the "extends" clause. // Class<?>[] interfaces = myClass.getInterfaces(); int interfaceCount = interfaces.length; for (int i = 0; i < interfaceCount; i++) { Class<?> iface = interfaces[i]; if (iface.getPackage().getName().equals(SQL_PACKAGE_NAME)) { vetInterfaceMethods(candidate, iface, unsupportedList, notUnderstoodList); } vetInterfaces(candidate, iface, unsupportedList, notUnderstoodList); } }
public void apply() throws IllegalAccessException, InvocationTargetException, InstantiationException { if (type.isEnum()) { for (T instance : type.getEnumConstants()) { assertThat( instance.toString(), is( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "." + ((Enum<?>) instance).name())); } return; } for (Constructor<?> constructor : type.getDeclaredConstructors()) { if (constructor.isSynthetic() && skipSynthetic) { continue; } constructor.setAccessible(true); Class<?>[] parameterTypes = constructor.getParameterTypes(); Object[] actualArguments = new Object[parameterTypes.length]; Object[] otherArguments = new Object[parameterTypes.length]; int index = 0; for (Class<?> parameterType : parameterTypes) { putInstance(parameterType, actualArguments, otherArguments, index++); } int testIndex = 0; @SuppressWarnings("unchecked") T instance = (T) constructor.newInstance(actualArguments); assertThat(instance, is(instance)); assertThat(instance, not(is((Object) null))); assertThat(instance, not(is(new Object()))); Object similarInstance = constructor.newInstance(actualArguments); assertThat(instance.hashCode(), is(similarInstance.hashCode())); assertThat(instance, is(similarInstance)); if (skipToString) { assertThat(instance.toString(), notNullValue()); } else if (optionalToStringRegex == null) { checkString(instance); } else { assertThat(instance.toString(), new RegexMatcher(optionalToStringRegex)); } for (Object otherArgument : otherArguments) { Object[] compareArguments = new Object[actualArguments.length]; int argumentIndex = 0; for (Object actualArgument : actualArguments) { if (argumentIndex == testIndex) { compareArguments[argumentIndex] = otherArgument; } else { compareArguments[argumentIndex] = actualArgument; } argumentIndex++; } Object unlikeInstance = constructor.newInstance(compareArguments); assertThat(instance.hashCode(), not(is(unlikeInstance))); assertThat(instance, not(is(unlikeInstance))); testIndex++; } } }
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()); }
protected void loadClassDependencies(Class aClass) throws ClassNotFoundException { String name = aClass.getName(); if (myVisited.add(aClass)) { try { for (Method method : aClass.getDeclaredMethods()) { loadTypeDependencies(method.getGenericReturnType()); for (Type type : method.getGenericExceptionTypes()) { loadTypeDependencies(type); } for (Type type : method.getGenericParameterTypes()) { loadTypeDependencies(type); } } for (Constructor method : aClass.getDeclaredConstructors()) { for (Type type : method.getGenericExceptionTypes()) { loadTypeDependencies(type); } for (Type type : method.getGenericParameterTypes()) { loadTypeDependencies(type); } } for (Field field : aClass.getDeclaredFields()) { loadTypeDependencies(field.getGenericType()); } Type superclass = aClass.getGenericSuperclass(); if (superclass != null) { loadClassDependencies(aClass); } for (Type intf : aClass.getGenericInterfaces()) { loadTypeDependencies(intf); } aClass.getAnnotations(); Package aPackage = aClass.getPackage(); if (aPackage != null) { aPackage.getAnnotations(); } } catch (LinkageError e) { throw new ClassNotFoundException(name); } catch (TypeNotPresentException e) { throw new ClassNotFoundException(name); } } }
private void checkString(T instance) { assertThat( instance.toString(), CoreMatchers.startsWith( type.getCanonicalName().substring(type.getPackage().getName().length() + 1) + "{")); assertThat(instance.toString(), endsWith("}")); Class<?> currentType = type; do { for (Field field : type.getDeclaredFields()) { if (!field.isSynthetic() && !Modifier.isStatic(field.getModifiers()) && !ignoredFields.contains(field.getName())) { assertThat(instance.toString(), containsString(field.getName())); } } } while ((currentType = currentType.getSuperclass()) != Object.class); }
public String getPublicMethodsForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); Method methods[] = c.getMethods(); Method method = null; result.append("<methods>"); if (methods != null) { for (int j = 0; j < methods.length; j++) { method = methods[j]; if (method != null && !methodsExclude.contains(method.getName())) { result.append("<method>"); result.append( (new StringBuilder("<methodSignature>")) .append(method.toString()) .append("</methodSignature>") .toString()); result.append( (new StringBuilder("<methodName>")) .append(method.getName()) .append("</methodName>") .toString()); result.append( (new StringBuilder("<returnType>")) .append(method.getReturnType().getName()) .append("</returnType>") .toString()); Class paramClasses[] = method.getParameterTypes(); result.append("<params>"); if (paramClasses != null) { for (int l = 0; l < paramClasses.length; l++) if (paramClasses[l] != null) result.append( (new StringBuilder("<param>")) .append(paramClasses[l].getName()) .append("</param>") .toString()); } result.append("</params>"); result.append("</method>"); } } } result.append("</methods>"); } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }
public String getPublicPropertiesForClasses(String classNames[]) { StringBuilder result = new StringBuilder(); String className = null; ArrayList publicFields = new ArrayList(); result.append("<classDefinitions>"); if (classNames != null && classNames.length > 0) { for (int i = 0; i < classNames.length; i++) { className = classNames[i]; if (className != null) { result.append("<classDefinition>"); try { Class c = Class.forName(className); Field fields[] = c.getFields(); Field field = null; if (fields != null) { for (int k = 0; k < fields.length; k++) { field = fields[k]; if (field != null) publicFields.add( (new StringBuilder(String.valueOf(field.getName()))) .append(",") .append(field.getType().getName()) .toString()); } } try { BeanInfo b = Introspector.getBeanInfo(c); result.append( (new StringBuilder("<classSimpleName>")) .append(c.getSimpleName()) .append("</classSimpleName>") .toString()); result.append( (new StringBuilder("<classFullName>")) .append(c.getName()) .append("</classFullName>") .toString()); Package pack = c.getPackage(); String packStr = ""; if (pack != null) packStr = pack.getName(); result.append( (new StringBuilder("<packageName>")) .append(packStr) .append("</packageName>") .toString()); PropertyDescriptor pds[] = b.getPropertyDescriptors(); if (pds != null) { for (int propCount = 0; propCount < pds.length; propCount++) { PropertyDescriptor pd = pds[propCount]; String propertyName = pd.getName(); Method readMethod = pd.getReadMethod(); Method writeMethod = pd.getWriteMethod(); if (readMethod != null && isPublicAccessor(readMethod.getModifiers()) && writeMethod != null && isPublicAccessor(writeMethod.getModifiers())) publicFields.add( (new StringBuilder(String.valueOf(propertyName))) .append(",") .append(pd.getPropertyType().getName()) .toString()); } } } catch (Exception e) { e.printStackTrace(); } if (publicFields != null && publicFields.size() > 0) { String temp = null; result.append("<publicFields>"); for (int counter = 0; counter < publicFields.size(); counter++) { temp = (String) publicFields.get(counter); if (temp != null) { String pubTemp[] = temp.split(","); if (pubTemp.length == 2) { result.append("<publicField>"); result.append( (new StringBuilder("<publicFieldName>")) .append(pubTemp[0]) .append("</publicFieldName>") .toString()); result.append( (new StringBuilder("<publicFieldType>")) .append(pubTemp[1]) .append("</publicFieldType>") .toString()); result.append("</publicField>"); } } } result.append("</publicFields>"); } } catch (ClassNotFoundException e) { result.append( (new StringBuilder("<classFullName>")) .append(className) .append("</classFullName>") .toString()); result.append( (new StringBuilder("<error>Problem retrieving ")) .append(className) .append(" information</error>") .toString()); System.out.println(e.getMessage()); } result.append("</classDefinition>"); } } } result.append("</classDefinitions>"); return result.toString(); }
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(); } }