List of usage examples for java.lang.reflect Constructor getName
@Override
public String getName()
From source file:RevEngAPI.java
/** Generate a .java file for the outline of the given class. */ public void doClass(Class c) throws IOException { className = c.getName();// w w w . ja v a 2 s . c o m // pre-compute offset for stripping package name classNameOffset = className.lastIndexOf('.') + 1; // Inner class if (className.indexOf('$') != -1) return; // get name, as String, with . changed to / String slashName = className.replace('.', '/'); String fileName = slashName + ".java"; System.out.println(className + " --> " + fileName); String dirName = slashName.substring(0, slashName.lastIndexOf("/")); new File(dirName).mkdirs(); // create the file. PrintWriter out = new PrintWriter(new FileWriter(fileName)); out.println("// Generated by RevEngAPI for class " + className); // If in a package, say so. Package pkg; if ((pkg = c.getPackage()) != null) { out.println("package " + pkg.getName() + ';'); out.println(); } // print class header int cMods = c.getModifiers(); printMods(cMods, out); out.print("class "); out.print(trim(c.getName())); out.print(' '); // XXX get superclass out.println('{'); // print constructors Constructor[] ctors = c.getDeclaredConstructors(); for (int i = 0; i < ctors.length; i++) { if (i == 0) { out.println(); out.println("\t// Constructors"); } Constructor cons = ctors[i]; int mods = cons.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(cons.getName()) + "("); Class[] classes = cons.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.print("\t}"); } // print method names Method[] mems = c.getDeclaredMethods(); for (int i = 0; i < mems.length; i++) { if (i == 0) { out.println(); out.println("\t// Methods"); } Method m = mems[i]; if (m.getName().startsWith("access$")) continue; int mods = m.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(m.getReturnType()); out.print(' '); out.print(trim(m.getName()) + "("); Class[] classes = m.getParameterTypes(); for (int j = 0; j < classes.length; j++) { if (j > 0) out.print(", "); out.print(trim(classes[j].getName()) + ' ' + mkName(PREFIX_ARG, j)); } out.println(") {"); out.println("\treturn " + defaultValue(m.getReturnType()) + ';'); out.println("\t}"); } // print fields Field[] flds = c.getDeclaredFields(); for (int i = 0; i < flds.length; i++) { if (i == 0) { out.println(); out.println("\t// Fields"); } Field f = flds[i]; int mods = f.getModifiers(); if (Modifier.isPrivate(mods)) continue; out.print('\t'); printMods(mods, out); out.print(trim(f.getType().getName())); out.print(' '); out.print(f.getName()); if (Modifier.isFinal(mods)) { try { out.print(" = " + f.get(null)); } catch (IllegalAccessException ex) { out.print("; // " + ex.toString()); } } out.println(';'); } out.println("}"); //out.flush(); out.close(); }
From source file:io.konik.utils.RandomInvoiceGenerator.java
private Object createNewInstance(Class<?> root) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { try {/*from w w w. j ava2s. c o m*/ if (root.isArray()) { Object[] array = (Object[]) Array.newInstance(root.getComponentType(), 1); Class<?> componentType = root.getComponentType(); array[0] = populteData(componentType, componentType.getName()); return array; } return root.newInstance(); } catch (IllegalAccessException e) { Constructor<?> biggestConstructor = findBiggestConstructor(root); //for each parameter populate data Class<?>[] constructorParameters = biggestConstructor.getParameterTypes(); Object[] constructorParameterObjects = new Object[constructorParameters.length]; for (int i = 0; i < constructorParameters.length; i++) { Class<?> cp = constructorParameters[i]; constructorParameterObjects[i] = populteData(cp, biggestConstructor.getName()); } return biggestConstructor.newInstance(constructorParameterObjects); } catch (InstantiationException e) { if (root.equals(CommonTax.class)) { // return ZfDateFactory.create(supportedDateFormatts[random.nextInt(3)]); } // throw e; e.printStackTrace(); return null; } }
From source file:com.github.hateoas.forms.spring.SpringActionDescriptor.java
static List<ActionParameterType> findConstructorInfo(final Class<?> beanType) { List<ActionParameterType> parametersInfo = new ArrayList<ActionParameterType>(); Constructor<?>[] constructors = beanType.getConstructors(); // find default ctor Constructor<?> constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); }/*w ww. ja va 2 s. c o m*/ if (constructor != null) { int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class<?>[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty for required fields -> String paramName = jsonProperty.value(); MethodParameter methodParameter = new MethodParameter(constructor, paramIndex); parametersInfo.add(new MethodParameterType(paramName, methodParameter)); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } } return parametersInfo; }
From source file:org.evosuite.setup.TestClusterGenerator.java
public static boolean canUse(Constructor<?> c) { if (c.isSynthetic()) { return false; }/*from ww w . ja va 2 s . c o m*/ // synthetic constructors are OK if (Modifier.isAbstract(c.getDeclaringClass().getModifiers())) return false; // TODO we could enable some methods from Object, like getClass //if (c.getDeclaringClass().equals(java.lang.Object.class)) // return false;// handled here to avoid printing reasons if (c.getDeclaringClass().equals(java.lang.Thread.class)) return false;// handled here to avoid printing reasons if (c.getDeclaringClass().isAnonymousClass()) return false; if (c.getDeclaringClass().isLocalClass()) { logger.debug("Skipping constructor of local class {}", c.getName()); return false; } if (c.getDeclaringClass().isMemberClass() && !canUse(c.getDeclaringClass())) return false; if (!Properties.USE_DEPRECATED && c.getAnnotation(Deprecated.class) != null) { logger.debug("Skipping deprecated constructor {}", c.getName()); return false; } if (isForbiddenNonDeterministicCall(c)) { return false; } if (Modifier.isPublic(c.getModifiers())) { makeAccessible(c); return true; } // If default access rights, then check if this class is in the same package as the target class if (!Modifier.isPrivate(c.getModifiers())) { // && !Modifier.isProtected(c.getModifiers())) { String packageName = ClassUtils.getPackageName(c.getDeclaringClass()); if (packageName.equals(Properties.CLASS_PREFIX)) { makeAccessible(c); return true; } } return false; }
From source file:de.escalon.hypermedia.spring.uber.UberUtils.java
/** * Renders input fields for bean properties of bean to add or update or patch. * * @param uberFields/*from w w w. j ava 2 s . c o m*/ * to add to * @param beanType * to render * @param annotatedParameters * which describes the method * @param annotatedParameter * which requires the bean * @param currentCallValue * sample call value */ private static void recurseBeanCreationParams(List<UberField> uberFields, Class<?> beanType, ActionDescriptor annotatedParameters, ActionInputParameter annotatedParameter, Object currentCallValue, String parentParamName, Set<String> knownFields) { // TODO collection, map and object node creation are only describable by an annotation, not via type reflection if (ObjectNode.class.isAssignableFrom(beanType) || Map.class.isAssignableFrom(beanType) || Collection.class.isAssignableFrom(beanType) || beanType.isArray()) { return; // use @Input(include) to list parameter names, at least? Or mix with hdiv's form builder? } try { Constructor[] constructors = beanType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } Assert.notNull(constructor, "no default constructor or JsonCreator found for type " + beanType.getName()); int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty for required fields String paramName = jsonProperty.value(); Class parameterType = parameters[paramIndex]; Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); MethodParameter methodParameter = new MethodParameter(constructor, paramIndex); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, paramName, parameterType, propertyValue, knownFields); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } Set<String> knownConstructorFields = new HashSet<String>(uberFields.size()); for (UberField sirenField : uberFields) { knownConstructorFields.add(sirenField.getName()); } // TODO support Option provider by other method args? Map<String, PropertyDescriptor> propertyDescriptors = PropertyUtils.getPropertyDescriptors(beanType); // add input field for every setter for (PropertyDescriptor propertyDescriptor : propertyDescriptors.values()) { final Method writeMethod = propertyDescriptor.getWriteMethod(); String propertyName = propertyDescriptor.getName(); if (writeMethod == null || knownFields.contains(parentParamName + propertyName)) { continue; } final Class<?> propertyType = propertyDescriptor.getPropertyType(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyName); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); addUberFieldsForMethodParameter(uberFields, methodParameter, annotatedParameter, annotatedParameters, parentParamName, propertyName, propertyType, propertyValue, knownConstructorFields); } } catch (Exception e) { throw new RuntimeException("Failed to write input fields for constructor", e); } }
From source file:org.apache.click.util.ContainerUtils.java
/** * This method ensures that the object can safely be navigated according * to the specified path.//from w w w . ja v a 2 s. com * <p/> * If any object in the graph is null, a new instance of that object class * is instantiated. * * @param object the object which path must be navigable without * encountering null values * @param path the navigation path */ private static void ensureObjectPathNotNull(Object object, String path) { final int index = path.indexOf('.'); if (index == -1) { return; } String property = path.substring(0, index); Method getterMethod = findGetter(object, property, path); Object result = invokeGetter(getterMethod, object, property, path); if (result == null) { // Find the target class of the object in the path to create Class<?> targetClass = getterMethod.getReturnType(); Constructor<?> constructor = null; try { // Lookup default no-arg constructor constructor = targetClass.getConstructor((Class[]) null); } catch (NoSuchMethodException e) { // Log detailed error message of looking up constructor failed HtmlStringBuffer buffer = new HtmlStringBuffer(); logBasicDescription(buffer, object, path, property); buffer.append("Attempt to construct instance of class '"); buffer.append(targetClass.getName()).append("' resulted in error: '"); buffer.append(targetClass.getName()).append("' does not seem"); buffer.append(" to have a default no argument constructor."); buffer.append(" Please note another common problem is that the"); buffer.append(" class is either not public or not static."); throw new RuntimeException(buffer.toString(), e); } try { // Create target object instance result = constructor.newInstance(new Object[] {}); } catch (Exception e) { // Log detailed error message of why creating target failed HtmlStringBuffer buffer = new HtmlStringBuffer(); logBasicDescription(buffer, object, path, property); buffer.append("Result: could not create"); buffer.append(" object with constructor '"); buffer.append(constructor.getName()).append("'."); throw new RuntimeException(buffer.toString(), e); } Method setterMethod = findSetter(object, property, targetClass, path); invokeSetter(setterMethod, object, result, property, path); } String remainingPath = path.substring(index + 1); ensureObjectPathNotNull(result, remainingPath); }
From source file:org.evosuite.setup.TestClusterGenerator.java
private boolean addDependencyClass(GenericClass clazz, int recursionLevel) { if (recursionLevel > Properties.CLUSTER_RECURSION) { logger.debug("Maximum recursion level reached, not adding dependency {}", clazz.getClassName()); return false; }/*from w ww . j av a2 s . c o m*/ clazz = clazz.getRawGenericClass(); if (analyzedClasses.contains(clazz.getRawClass())) { return true; } analyzedClasses.add(clazz.getRawClass()); // We keep track of generic containers in case we find other concrete generic components during runtime if (clazz.isAssignableTo(Collection.class) || clazz.isAssignableTo(Map.class)) { if (clazz.getNumParameters() > 0) { containerClasses.add(clazz.getRawClass()); } } if (clazz.equals(String.class)) { return false; } try { TestCluster cluster = TestCluster.getInstance(); logger.debug("Adding dependency class {}", clazz.getClassName()); // TODO: Should we include declared classes as well? if (!canUse(clazz.getRawClass())) { logger.info("*** Cannot use class: {}", clazz.getClassName()); return false; } // Add all constructors for (Constructor<?> constructor : getConstructors(clazz.getRawClass())) { String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), "<init>", org.objectweb.asm.Type.getConstructorDescriptor(constructor)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(constructor)) { GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz); try { cluster.addGenerator(clazz.getWithWildcardTypes(), genericConstructor); addDependencies(genericConstructor, recursionLevel + 1); logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(), constructor.getName(), Type.getConstructorDescriptor(constructor)); } catch (Throwable t) { logger.info("Error adding constructor {}: {}", constructor.getName(), t.getMessage()); } } else { logger.debug("Constructor cannot be used: {}", constructor); } } // Add all methods for (Method method : getMethods(clazz.getRawClass())) { String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getClassName(), method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(method, clazz.getRawClass()) && !method.getName().equals("hashCode")) { logger.debug("Adding method {}.{}{}", clazz.getClassName(), method.getName(), Type.getMethodDescriptor(method)); if (method.getTypeParameters().length > 0) { logger.info("Type parameters in methods are not handled yet, skipping {}", method); continue; } GenericMethod genericMethod = new GenericMethod(method, clazz); try { addDependencies(genericMethod, recursionLevel + 1); cluster.addModifier(clazz.getWithWildcardTypes(), genericMethod); // GenericClass retClass = new GenericClass( // genericMethod.getReturnType(), method.getReturnType()); GenericClass retClass = new GenericClass(method.getReturnType()); if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) { cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod); } } catch (Throwable t) { logger.info("Error adding method {}: {}", method.getName(), t.getMessage()); } } else { logger.debug("Method cannot be used: {}", method); } } // Add all fields for (Field field : getFields(clazz.getRawClass())) { logger.debug("Checking field {}", field); if (canUse(field, clazz.getRawClass())) { logger.debug("Adding field {} for class {}", field, clazz); try { GenericField genericField = new GenericField(field, clazz); cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(), genericField); if (!Modifier.isFinal(field.getModifiers())) { cluster.addModifier(clazz.getWithWildcardTypes(), genericField); addDependencies(genericField, recursionLevel + 1); } } catch (Throwable t) { logger.info("Error adding field {}: {}", field.getName(), t.getMessage()); } } else { logger.debug("Field cannot be used: {}", field); } } logger.info("Finished analyzing {} at recursion level {}", clazz.getTypeName(), recursionLevel); cluster.getAnalyzedClasses().add(clazz.getRawClass()); } catch (Throwable t) { /* * NOTE: this is a problem we know it can happen in some cases in SF110, but don't * have a real solution now. As it is bound to happen, we try to minimize the logging (eg no * stack trace), although we still need to log it */ logger.error("Problem for {}. Failed to add dependencies for class {}: {}\n{}", Properties.TARGET_CLASS, clazz.getClassName(), t, Arrays.asList(t.getStackTrace())); return false; } return true; }
From source file:de.escalon.hypermedia.spring.hydra.LinkListSerializer.java
/** * Writes bean description recursively./*w ww .j a v a 2 s. c o m*/ * * @param jgen * to write to * @param currentVocab * in context * @param valueType * class of value * @param allRootParameters * of the method that receives the request body * @param rootParameter * the request body * @param currentCallValue * the value at the current recursion level * @param propertyPath * of the current recursion level * @throws IntrospectionException * @throws IOException */ private void recurseSupportedProperties(JsonGenerator jgen, String currentVocab, Class<?> valueType, ActionDescriptor allRootParameters, ActionInputParameter rootParameter, Object currentCallValue, String propertyPath) throws IntrospectionException, IOException { Map<String, ActionInputParameter> properties = new HashMap<String, ActionInputParameter>(); // collect supported properties from ctor Constructor[] constructors = valueType.getConstructors(); // find default ctor Constructor constructor = PropertyUtils.findDefaultCtor(constructors); // find ctor with JsonCreator ann if (constructor == null) { constructor = PropertyUtils.findJsonCreator(constructors, JsonCreator.class); } if (constructor == null) { // TODO this can be a generic collection, find a way to describe it LOG.warn("can't describe supported properties, no default constructor or JsonCreator found for type " + valueType.getName()); return; } int parameterCount = constructor.getParameterTypes().length; if (parameterCount > 0) { Annotation[][] annotationsOnParameters = constructor.getParameterAnnotations(); Class[] parameters = constructor.getParameterTypes(); int paramIndex = 0; for (Annotation[] annotationsOnParameter : annotationsOnParameters) { for (Annotation annotation : annotationsOnParameter) { if (JsonProperty.class == annotation.annotationType()) { JsonProperty jsonProperty = (JsonProperty) annotation; // TODO use required attribute of JsonProperty String paramName = jsonProperty.value(); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, paramName); ActionInputParameter constructorParamInputParameter = new SpringActionInputParameter( new MethodParameter(constructor, paramIndex), propertyValue); // TODO collect ctor params, setter params and process // TODO then handle single, collection and bean for both properties.put(paramName, constructorParamInputParameter); paramIndex++; // increase for each @JsonProperty } } } Assert.isTrue(parameters.length == paramIndex, "not all constructor arguments of @JsonCreator " + constructor.getName() + " are annotated with @JsonProperty"); } // collect supported properties from setters // TODO support Option provider by other method args? final BeanInfo beanInfo = Introspector.getBeanInfo(valueType); final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); // TODO collection and map // TODO distinguish which properties should be printed as supported - now just setters for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { final Method writeMethod = propertyDescriptor.getWriteMethod(); if (writeMethod == null) { continue; } // TODO: the property name must be a valid URI - need to check context for terms? String propertyName = getWritableExposedPropertyOrPropertyName(propertyDescriptor); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, propertyDescriptor.getName()); MethodParameter methodParameter = new MethodParameter(propertyDescriptor.getWriteMethod(), 0); ActionInputParameter propertySetterInputParameter = new SpringActionInputParameter(methodParameter, propertyValue); properties.put(propertyName, propertySetterInputParameter); } // write all supported properties // TODO we are using the annotatedParameter.parameterName but should use the key of properties here: for (ActionInputParameter annotatedParameter : properties.values()) { String nextPropertyPathLevel = propertyPath.isEmpty() ? annotatedParameter.getParameterName() : propertyPath + '.' + annotatedParameter.getParameterName(); if (DataType.isSingleValueType(annotatedParameter.getParameterType())) { final Object[] possiblePropertyValues = rootParameter.getPossibleValues(allRootParameters); if (rootParameter.isIncluded(nextPropertyPathLevel) && !rootParameter.isExcluded(nextPropertyPathLevel)) { writeSupportedProperty(jgen, currentVocab, annotatedParameter, annotatedParameter.getParameterName(), possiblePropertyValues); } // TODO collections? // } else if (DataType.isArrayOrCollection(parameterType)) { // Object[] callValues = rootParameter.getValues(); // int items = callValues.length; // for (int i = 0; i < items; i++) { // Object value; // if (i < callValues.length) { // value = callValues[i]; // } else { // value = null; // } // recurseSupportedProperties(jgen, currentVocab, rootParameter // .getParameterType(), // allRootParameters, rootParameter, value); // } } else { jgen.writeStartObject(); jgen.writeStringField("hydra:property", annotatedParameter.getParameterName()); // TODO: is the property required -> for bean props we need the Access annotation to express that jgen.writeObjectFieldStart(getPropertyOrClassNameInVocab(currentVocab, "rangeIncludes", LdContextFactory.HTTP_SCHEMA_ORG, "schema:")); Expose expose = AnnotationUtils.getAnnotation(annotatedParameter.getParameterType(), Expose.class); String subClass; if (expose != null) { subClass = expose.value(); } else { subClass = annotatedParameter.getParameterType().getSimpleName(); } jgen.writeStringField(getPropertyOrClassNameInVocab(currentVocab, "subClassOf", "http://www.w3" + ".org/2000/01/rdf-schema#", "rdfs:"), subClass); jgen.writeArrayFieldStart("hydra:supportedProperty"); Object propertyValue = PropertyUtils.getPropertyOrFieldValue(currentCallValue, annotatedParameter.getParameterName()); recurseSupportedProperties(jgen, currentVocab, annotatedParameter.getParameterType(), allRootParameters, rootParameter, propertyValue, nextPropertyPathLevel); jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndObject(); } } }
From source file:org.evosuite.setup.TestClusterGenerator.java
/** * All public methods defined directly in the SUT should be covered * /*from w w w . ja va 2 s . c o m*/ * TODO: What if we use instrument_parent? * * @param targetClass */ @SuppressWarnings("unchecked") private void initializeTargetMethods() throws RuntimeException, ClassNotFoundException { logger.info("Analyzing target class"); Class<?> targetClass = Properties.getTargetClass(); TestCluster cluster = TestCluster.getInstance(); Set<Class<?>> targetClasses = new LinkedHashSet<Class<?>>(); if (targetClass == null) { throw new RuntimeException("Failed to load " + Properties.TARGET_CLASS); } targetClasses.add(targetClass); addDeclaredClasses(targetClasses, targetClass); if (Modifier.isAbstract(targetClass.getModifiers())) { logger.info("SUT is an abstract class"); Set<Class<?>> subclasses = getConcreteClasses(targetClass, inheritanceTree); logger.info("Found {} concrete subclasses", subclasses.size()); targetClasses.addAll(subclasses); } // To make sure we also have anonymous inner classes double check inner classes using ASM ClassNode targetClassNode = DependencyAnalysis.getClassNode(Properties.TARGET_CLASS); Queue<InnerClassNode> innerClasses = new LinkedList<InnerClassNode>(); innerClasses.addAll(targetClassNode.innerClasses); while (!innerClasses.isEmpty()) { InnerClassNode icn = innerClasses.poll(); try { logger.debug("Loading inner class: {}, {},{}", icn.innerName, icn.name, icn.outerName); String innerClassName = ResourceList.getClassNameFromResourcePath(icn.name); Class<?> innerClass = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(innerClassName); //if (!canUse(innerClass)) // continue; // Sometimes strange things appear such as Map$Entry if (!targetClasses.contains(innerClass)) { // && !innerClassName.matches(".*\\$\\d+(\\$.*)?$")) { logger.info("Adding inner class {}", innerClassName); targetClasses.add(innerClass); ClassNode innerClassNode = DependencyAnalysis.getClassNode(innerClassName); innerClasses.addAll(innerClassNode.innerClasses); } } catch (Throwable t) { logger.error("Problem for {}. Error loading inner class: {}, {},{}: {}", Properties.TARGET_CLASS, icn.innerName, icn.name, icn.outerName, t); } } for (Class<?> clazz : targetClasses) { logger.info("Current SUT class: {}", clazz); if (!canUse(clazz)) { logger.info("Cannot access SUT class: {}", clazz); continue; } // Add all constructors for (Constructor<?> constructor : getConstructors(clazz)) { logger.info("Checking target constructor {}", constructor); String name = "<init>" + org.objectweb.asm.Type.getConstructorDescriptor(constructor); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), "<init>", org.objectweb.asm.Type.getConstructorDescriptor(constructor)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(constructor)) { GenericConstructor genericConstructor = new GenericConstructor(constructor, clazz); cluster.addTestCall(genericConstructor); // TODO: Add types! cluster.addGenerator(new GenericClass(clazz).getWithWildcardTypes(), genericConstructor); addDependencies(genericConstructor, 1); logger.debug("Keeping track of {}.{}{}", constructor.getDeclaringClass().getName(), constructor.getName(), Type.getConstructorDescriptor(constructor)); } else { logger.debug("Constructor cannot be used: {}", constructor); } } // Add all methods for (Method method : getMethods(clazz)) { logger.info("Checking target method {}", method); String name = method.getName() + org.objectweb.asm.Type.getMethodDescriptor(method); if (Properties.TT) { String orig = name; name = BooleanTestabilityTransformation.getOriginalNameDesc(clazz.getName(), method.getName(), org.objectweb.asm.Type.getMethodDescriptor(method)); if (!orig.equals(name)) logger.info("TT name: {} -> {}", orig, name); } if (canUse(method, clazz)) { logger.debug("Adding method {}.{}{}", clazz.getName(), method.getName(), Type.getMethodDescriptor(method)); GenericMethod genericMethod = new GenericMethod(method, clazz); cluster.addTestCall(genericMethod); cluster.addModifier(new GenericClass(clazz).getWithWildcardTypes(), genericMethod); addDependencies(genericMethod, 1); GenericClass retClass = new GenericClass(method.getReturnType()); if (!retClass.isPrimitive() && !retClass.isVoid() && !retClass.isObject()) cluster.addGenerator(retClass.getWithWildcardTypes(), genericMethod); } else { logger.debug("Method cannot be used: {}", method); } } for (Field field : getFields(clazz)) { logger.info("Checking target field {}", field); if (canUse(field, clazz)) { GenericField genericField = new GenericField(field, clazz); addDependencies(genericField, 1); cluster.addGenerator(new GenericClass(field.getGenericType()).getWithWildcardTypes(), genericField); logger.debug("Adding field {}", field); if (!Modifier.isFinal(field.getModifiers())) { logger.debug("Is not final"); cluster.addTestCall(new GenericField(field, clazz)); } else { logger.debug("Is final"); if (Modifier.isStatic(field.getModifiers()) && !field.getType().isPrimitive()) { logger.debug("Is static non-primitive"); /* * With this we are trying to cover such cases: * public static final DurationField INSTANCE = new MillisDurationField(); private MillisDurationField() { super(); } */ try { Object o = field.get(null); if (o == null) { logger.info("Field is not yet initialized: {}", field); } else { Class<?> actualClass = o.getClass(); logger.debug("Actual class is {}", actualClass); if (!actualClass.isAssignableFrom(genericField.getRawGeneratedType()) && genericField.getRawGeneratedType().isAssignableFrom(actualClass)) { GenericField superClassField = new GenericField(field, clazz); cluster.addGenerator(new GenericClass(actualClass), superClassField); } } } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } else { logger.debug("Can't use field {}", field); } } analyzedClasses.add(clazz); // TODO: Set to generic type rather than class? cluster.getAnalyzedClasses().add(clazz); } if (Properties.INSTRUMENT_PARENT) { for (String superClass : inheritanceTree.getSuperclasses(Properties.TARGET_CLASS)) { try { Class<?> superClazz = TestGenerationContext.getInstance().getClassLoaderForSUT() .loadClass(superClass); dependencies.add(new Pair(0, superClazz)); } catch (ClassNotFoundException e) { logger.error("Problem for {}. Class not found: {}", Properties.TARGET_CLASS, superClass, e); } } } if (Properties.HANDLE_STATIC_FIELDS) { GetStaticGraph getStaticGraph = GetStaticGraphGenerator.generate(Properties.TARGET_CLASS); Map<String, Set<String>> staticFields = getStaticGraph.getStaticFields(); for (String className : staticFields.keySet()) { logger.info("Adding static fields to cluster for class {}", className); Class<?> clazz; try { clazz = getClass(className); } catch (ExceptionInInitializerError ex) { logger.debug("Class class init caused exception {}", className); continue; } if (clazz == null) { logger.debug("Class not found {}", className); continue; } if (!canUse(clazz)) continue; Set<String> fields = staticFields.get(className); for (Field field : getFields(clazz)) { if (!canUse(field, clazz)) continue; if (fields.contains(field.getName())) { if (!Modifier.isFinal(field.getModifiers())) { logger.debug("Is not final"); cluster.addTestCall(new GenericField(field, clazz)); } } } } PutStaticMethodCollector collector = new PutStaticMethodCollector(Properties.TARGET_CLASS, staticFields); Set<MethodIdentifier> methodIdentifiers = collector.collectMethods(); for (MethodIdentifier methodId : methodIdentifiers) { Class<?> clazz = getClass(methodId.getClassName()); if (clazz == null) continue; if (!canUse(clazz)) continue; Method method = getMethod(clazz, methodId.getMethodName(), methodId.getDesc()); if (method == null) continue; GenericMethod genericMethod = new GenericMethod(method, clazz); cluster.addTestCall(genericMethod); } } logger.info("Finished analyzing target class"); }