Example usage for java.lang.reflect Constructor getDeclaringClass

List of usage examples for java.lang.reflect Constructor getDeclaringClass

Introduction

In this page you can find the example usage for java.lang.reflect Constructor getDeclaringClass.

Prototype

@Override
public Class<T> getDeclaringClass() 

Source Link

Document

Returns the Class object representing the class that declares the constructor represented by this object.

Usage

From source file:org.apache.bval.jsr.ClassValidator.java

public <T> Set<ConstraintViolation<T>> validateConstructorReturnValue(
        final Constructor<? extends T> constructor, final T createdObject, final Class<?>... gps) {
    {//from   w w  w.j  av a  2s  .c  o m
        notNull("Constructor", constructor);
        notNull("Returned value", createdObject);
    }

    final Class<? extends T> declaringClass = constructor.getDeclaringClass();
    final ConstructorDescriptorImpl methodDescriptor = ConstructorDescriptorImpl.class
            .cast(getConstraintsForClass(declaringClass)
                    .getConstraintsForConstructor(constructor.getParameterTypes()));
    if (methodDescriptor == null) {
        throw new ValidationException(
                "Constructor " + constructor + " doesn't belong to class " + declaringClass);
    }

    return validaReturnedValue(
            new NodeImpl.ConstructorNodeImpl(declaringClass.getSimpleName(),
                    Arrays.asList(constructor.getParameterTypes())),
            createdObject, declaringClass, methodDescriptor, gps, null);
}

From source file:org.apache.bval.jsr.ClassValidator.java

public <T> Set<ConstraintViolation<T>> validateConstructorParameters(Constructor<? extends T> constructor,
        Object[] parameterValues, Class<?>... gps) {
    notNull("Constructor", constructor);
    notNull("Groups", gps);
    notNull("Parameters", parameterValues);

    final Class<?> declaringClass = constructor.getDeclaringClass();
    final ConstructorDescriptorImpl constructorDescriptor = ConstructorDescriptorImpl.class
            .cast(getConstraintsForClass(declaringClass)
                    .getConstraintsForConstructor(constructor.getParameterTypes()));
    if (constructorDescriptor == null) { // no constraint
        return Collections.emptySet();
    }//  www.j  a v a2  s.  c  om

    // sanity checks
    if (!constructorDescriptor.isValidated(constructor)) {
        if (parameterValues.length == 0) {
            checkValidationAppliesTo(Collections.singleton(constructorDescriptor.getCrossParameterDescriptor()),
                    ConstraintTarget.PARAMETERS);
            checkValidationAppliesTo(constructorDescriptor.getParameterDescriptors(),
                    ConstraintTarget.PARAMETERS);
        } else {
            checkValidationAppliesTo(Collections.singleton(constructorDescriptor.getCrossParameterDescriptor()),
                    ConstraintTarget.IMPLICIT);
            checkValidationAppliesTo(constructorDescriptor.getParameterDescriptors(),
                    ConstraintTarget.IMPLICIT);
        }
        constructorDescriptor.setValidated(constructor);
    }

    // validations
    return validateInvocationParameters(constructor, parameterValues, constructorDescriptor, gps,
            new NodeImpl.ConstructorNodeImpl(declaringClass.getSimpleName(),
                    Arrays.asList(constructor.getParameterTypes())),
            null);
}

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   ww w.  j  a  v  a  2  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:org.evosuite.setup.TestClusterGenerator.java

/**
 * All public methods defined directly in the SUT should be covered
 * /*from ww  w .  j  av a2 s  .  co 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");
}

From source file:com.clark.func.Functions.java

/**
 * Returns accessible version of the given constructor.
 * /*from   w  ww  . ja  va  2 s  .  c o m*/
 * @param ctor
 *            prototype constructor object.
 * @return <code>null</code> if accessible constructor can not be found.
 * @see java.lang.SecurityManager
 */
public static <T> Constructor<T> getAccessibleConstructor(Constructor<T> ctor) {
    return isAccessible(ctor) && Modifier.isPublic(ctor.getDeclaringClass().getModifiers()) ? ctor : null;
}