Example usage for java.lang.reflect Constructor isSynthetic

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

Introduction

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

Prototype

@Override
public boolean isSynthetic() 

Source Link

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Constructor[] constructors = ArrayList.class.getDeclaredConstructors();

    for (int i = 0; i < constructors.length; i++) {
        Constructor c = constructors[i];
        System.out.println(c.isSynthetic());
    }/*www.  j  av  a  2 s  .  c  om*/
}

From source file:Main.java

public static void main(String... args) throws Exception {
    Class<?> c = Class.forName(args[0]);
    Constructor[] allConstructors = c.getDeclaredConstructors();
    for (Constructor ctor : allConstructors) {
        int searchMod = modifierFromString(args[1]);
        int mods = accessModifiers(ctor.getModifiers());
        if (searchMod == mods) {
            out.format("%s%n", ctor.toGenericString());
            out.format("  [ synthetic=%-5b var_args=%-5b ]%n", ctor.isSynthetic(), ctor.isVarArgs());
        }//from   w w  w .  j  a  va  2s . c o  m
    }
}

From source file:ConstructorAccess.java

public static void main(String... args) {
    try {// www  .j a v  a 2  s. c  om
        Class<?> c = Class.forName(args[0]);
        Constructor[] allConstructors = c.getDeclaredConstructors();
        for (Constructor ctor : allConstructors) {
            int searchMod = modifierFromString(args[1]);
            int mods = accessModifiers(ctor.getModifiers());
            if (searchMod == mods) {
                out.format("%s%n", ctor.toGenericString());
                out.format("  [ synthetic=%-5b var_args=%-5b ]%n", ctor.isSynthetic(), ctor.isVarArgs());
            }
        }

        // production code should handle this exception more gracefully
    } catch (ClassNotFoundException x) {
        x.printStackTrace();
    }
}

From source file:hu.bme.mit.sette.common.validator.reflection.ConstructorValidator.java

/**
 * Sets whether the constructor should be synthetic or not.
 *
 * @param isSynthetic/*  w w  w  .j  a v  a  2s . co m*/
 *            true if the constructor should be synthetic, false if it
 *            should not be
 * @return this object
 */
public ConstructorValidator synthetic(final boolean isSynthetic) {
    if (getSubject() != null) {
        Constructor<?> constructor = getSubject();

        if (isSynthetic ^ constructor.isSynthetic()) {
            String must;

            if (isSynthetic) {
                must = "must";
            } else {
                must = "must not";
            }

            this.addException(String.format("The constructor %s be synthetic", must));
        }
    }

    return this;
}

From source file:hu.bme.mit.sette.common.model.snippet.Snippet.java

/**
 * Parses the methods which should be considered in coverage.
 *
 * @param annotation/*  www.ja va2 s . c om*/
 *            the {@link SetteIncludeCoverage} annotation
 * @param v
 *            a {@link MethodValidator}
 * @param classLoader
 *            the class loader for loading snippet project classes
 */
private void parseIncludedMethods(final SetteIncludeCoverage annotation, final MethodValidator v,
        final ClassLoader classLoader) {
    if (annotation == null) {
        return;
    }

    Class<?>[] includedClasses = annotation.classes();
    String[] includedMethodStrings = annotation.methods();
    boolean shouldParse = true; // only parse if no validation error

    // check the arrays: not empty, no null element, same lengths
    if (ArrayUtils.isEmpty(includedClasses)) {
        v.addException("The included class list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedClasses, null)) {
        v.addException("The included class list " + "must not contain null elements");
        shouldParse = false;
    }

    if (ArrayUtils.isEmpty(includedMethodStrings)) {
        v.addException("The included method list must not be empty");
        shouldParse = false;
    }

    if (ArrayUtils.contains(includedMethodStrings, null)) {
        v.addException("The included method list " + "must not contain null elements");
        shouldParse = false;
    }

    if (!ArrayUtils.isSameLength(includedClasses, includedMethodStrings)) {
        v.addException("The included class list and method list " + "must have the same length");
        shouldParse = false;
    }

    if (shouldParse) {
        // check and add methods
        for (int i = 0; i < includedClasses.length; i++) {
            Class<?> includedClass = includedClasses[i];
            String includedMethodString = includedMethodStrings[i].trim();

            if (includedMethodString.equals("*")) {
                // add all non-synthetic constructors
                for (Constructor<?> c : includedClass.getDeclaredConstructors()) {
                    if (!c.isSynthetic()) {
                        addIncludedConstructor(c, v);
                    }
                }
                // add all non-synthetic methods
                for (Method m : includedClass.getDeclaredMethods()) {
                    if (!m.isSynthetic()) {
                        addIncludedMethod(m, v);
                    }
                }
            } else {
                parseIncludedMethod(includedClass, includedMethodString, v, classLoader);
            }
        }
    }
}

From source file:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Constructor<?> c) {

    if (c.isSynthetic()) {
        return false;
    }//from w ww  .ja  v a2 s . co  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:org.evosuite.setup.TestUsageChecker.java

public static boolean canUse(Constructor<?> c) {

    if (c.isSynthetic()) {
        return false;
    }//from w ww  .j  a  v a 2s .co  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() && !TestUsageChecker.canUse(c.getDeclaringClass()))
        return false;

    if (!Properties.USE_DEPRECATED && c.isAnnotationPresent(Deprecated.class)) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
        if (Properties.hasTargetClassBeenLoaded() && !c.getDeclaringClass().equals(targetClass)) {
            logger.debug("Excluding deprecated constructor " + c.getName());
            return false;
        }
    }

    if (isForbiddenNonDeterministicCall(c)) {
        return false;
    }

    if (Modifier.isPublic(c.getModifiers())) {
        TestClusterUtils.makeAccessible(c);
        return true;
    }

    for (java.lang.reflect.Type paramType : c.getGenericParameterTypes()) {
        if (!canUse(paramType))
            return false;
    }

    // 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)) {
            TestClusterUtils.makeAccessible(c);
            return true;
        }
    }

    return false;
}

From source file:org.lunarray.model.descriptor.creational.util.CreationalScanUtil.java

/**
 * Find a no-args public constructor./*  www  .j  av  a  2 s .  co m*/
 * 
 * @param source
 *            The source class. May not be null.
 * @return The constructor, or null.
 * @param <E>
 *            The entity type.
 */
@SuppressWarnings("unchecked")
public static <E> Constructor<E> findConstructor(final Class<E> source) {
    Validate.notNull(source, "Source may not be null.");
    Constructor<E> result = null;
    if (!Modifier.isAbstract(source.getModifiers()) && !source.isSynthetic()) {
        for (final Constructor<E> constructor : (Constructor<E>[]) source.getConstructors()) {
            if (!constructor.isSynthetic() && (constructor.getParameterTypes().length == 0)) {
                result = constructor;
            }
        }
    }
    return result;
}

From source file:org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.java

@Override
@Nullable/*from   www  .  ja  v a 2  s  .c  om*/
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
        throws BeanCreationException {

    // Let's check for lookup methods here..
    if (!this.lookupMethodsChecked.contains(beanName)) {
        try {
            ReflectionUtils.doWithMethods(beanClass, method -> {
                Lookup lookup = method.getAnnotation(Lookup.class);
                if (lookup != null) {
                    Assert.state(beanFactory != null, "No BeanFactory available");
                    LookupOverride override = new LookupOverride(method, lookup.value());
                    try {
                        RootBeanDefinition mbd = (RootBeanDefinition) beanFactory
                                .getMergedBeanDefinition(beanName);
                        mbd.getMethodOverrides().addOverride(override);
                    } catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(beanName,
                                "Cannot apply @Lookup to beans without corresponding bean definition");
                    }
                }
            });
        } catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
        }
        this.lookupMethodsChecked.add(beanName);
    }

    // Quick check on the concurrent map first, with minimal locking.
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        synchronized (this.candidateConstructorsCache) {
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                Constructor<?>[] rawCandidates;
                try {
                    rawCandidates = beanClass.getDeclaredConstructors();
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName()
                                    + "] from ClassLoader [" + beanClass.getClassLoader() + "] failed",
                            ex);
                }
                List<Constructor<?>> candidates = new ArrayList<>(rawCandidates.length);
                Constructor<?> requiredConstructor = null;
                Constructor<?> defaultConstructor = null;
                Constructor<?> primaryConstructor = BeanUtils.findPrimaryConstructor(beanClass);
                int nonSyntheticConstructors = 0;
                for (Constructor<?> candidate : rawCandidates) {
                    if (!candidate.isSynthetic()) {
                        nonSyntheticConstructors++;
                    } else if (primaryConstructor != null) {
                        continue;
                    }
                    AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor = userClass
                                        .getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            } catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    if (ann != null) {
                        if (requiredConstructor != null) {
                            throw new BeanCreationException(beanName, "Invalid autowire-marked constructor: "
                                    + candidate
                                    + ". Found constructor with 'required' Autowired annotation already: "
                                    + requiredConstructor);
                        }
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructors: " + candidates
                                                + ". Found constructor with 'required' Autowired annotation: "
                                                + candidate);
                            }
                            requiredConstructor = candidate;
                        }
                        candidates.add(candidate);
                    } else if (candidate.getParameterCount() == 0) {
                        defaultConstructor = candidate;
                    }
                }
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    if (requiredConstructor == null) {
                        if (defaultConstructor != null) {
                            candidates.add(defaultConstructor);
                        } else if (candidates.size() == 1 && logger.isWarnEnabled()) {
                            logger.warn("Inconsistent constructor declaration on bean with name '" + beanName
                                    + "': single autowire-marked constructor flagged as optional - "
                                    + "this constructor is effectively required since there is no "
                                    + "default constructor to fall back to: " + candidates.get(0));
                        }
                    }
                    candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
                } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterCount() > 0) {
                    candidateConstructors = new Constructor<?>[] { rawCandidates[0] };
                } else if (nonSyntheticConstructors == 2 && primaryConstructor != null
                        && defaultConstructor != null && !primaryConstructor.equals(defaultConstructor)) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor, defaultConstructor };
                } else if (nonSyntheticConstructors == 1 && primaryConstructor != null) {
                    candidateConstructors = new Constructor<?>[] { primaryConstructor };
                } else {
                    candidateConstructors = new Constructor<?>[0];
                }
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}