Example usage for java.lang Class getModifiers

List of usage examples for java.lang Class getModifiers

Introduction

In this page you can find the example usage for java.lang Class getModifiers.

Prototype

@HotSpotIntrinsicCandidate
public native int getModifiers();

Source Link

Document

Returns the Java language modifiers for this class or interface, encoded in an integer.

Usage

From source file:org.apache.tapestry.enhance.DefaultComponentClassEnhancer.java

/**
 *  Invoked to validate that an enhanced class is acceptible.  Primarily, this is to ensure
 *  that the class contains no unimplemented abstract methods or fields.  Normally,
 *  this kind of checking is done at compile time, but for generated
 *  classes, there is no compile time check (!) and you can get runtime
 *  errors when accessing unimplemented abstract methods.
 * /*from w w w . j a va2  s  .  c o  m*/
 *
 **/

protected void validateEnhancedClass(Class subject, String className, IComponentSpecification specification) {
    boolean debug = LOG.isDebugEnabled();

    if (debug)
        LOG.debug("Validating " + subject);

    Set implementedMethods = new HashSet();
    Class current = subject;

    while (true) {
        Method m = checkForAbstractMethods(current, implementedMethods);

        if (m != null)
            throw new ApplicationRuntimeException(
                    Tapestry.format("DefaultComponentClassEnhancer.no-impl-for-abstract-method",
                            new Object[] { m, current, className, subject.getName() }),
                    specification.getLocation(), null);

        // An earlier version of this code walked the interfaces directly,
        // but it appears that implementing an interface actually
        // puts abstract method declarations into the class
        // (at least, in terms of what getDeclaredMethods() returns).

        // March up to the super class.

        current = current.getSuperclass();

        // Once advanced up to a concrete class, we trust that
        // the compiler did its checking.

        if (!Modifier.isAbstract(current.getModifiers()))
            break;
    }

}

From source file:com.opensymphony.xwork3.config.providers.XmlConfigurationProvider.java

protected boolean verifyAction(String className, String name) {
    if (className.indexOf('{') > -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Action class [" + className + "] contains a wildcard "
                    + "replacement value, so it can't be verified");
        }//from   ww w .j av  a 2  s .c  o  m
        return true;
    }
    try {
        if (objectFactory.isNoArgConstructorRequired()) {
            Class clazz = objectFactory.getClassInstance(className);
            if (!Modifier.isPublic(clazz.getModifiers())) {
                throw new ConfigurationException("Action class [" + className + "] is not public");
            }
            clazz.getConstructor(new Class[] {});
        }
    } catch (ClassNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Class not found for action [#0]", e, className);
        }
        throw new ConfigurationException("Action class [" + className + "] not found");
    } catch (NoSuchMethodException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No constructor found for action [#0]", e, className);
        }
        throw new ConfigurationException(
                "Action class [" + className + "] does not have a public no-arg constructor", e);
    } catch (RuntimeException ex) {
        // Probably not a big deal, like request or session-scoped Spring 2 beans that need a real request
        if (LOG.isInfoEnabled()) {
            LOG.info("Unable to verify action class [#0] exists at initialization", className);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Action verification cause", ex);
        }
    } catch (Exception ex) {
        // Default to failing fast
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to verify action class [#0]", ex, className);
        }
        throw new ConfigurationException(ex);
    }
    return true;
}

From source file:com.opensymphony.xwork2.config.providers.XmlConfigurationProvider.java

protected boolean verifyAction(String className, String name, Location loc) {
    if (className.indexOf('{') > -1) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Action class [" + className + "] contains a wildcard "
                    + "replacement value, so it can't be verified");
        }/*  w  w  w  .  j  av  a 2s.  c  om*/
        return true;
    }
    try {
        if (objectFactory.isNoArgConstructorRequired()) {
            Class clazz = objectFactory.getClassInstance(className);
            if (!Modifier.isPublic(clazz.getModifiers())) {
                throw new ConfigurationException("Action class [" + className + "] is not public", loc);
            }
            clazz.getConstructor(new Class[] {});
        }
    } catch (ClassNotFoundException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Class not found for action [#0]", e, className);
        }
        throw new ConfigurationException("Action class [" + className + "] not found", loc);
    } catch (NoSuchMethodException e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("No constructor found for action [#0]", e, className);
        }
        throw new ConfigurationException(
                "Action class [" + className + "] does not have a public no-arg constructor", e, loc);
    } catch (RuntimeException ex) {
        // Probably not a big deal, like request or session-scoped Spring 2 beans that need a real request
        if (LOG.isInfoEnabled()) {
            LOG.info("Unable to verify action class [#0] exists at initialization", className);
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Action verification cause", ex);
        }
    } catch (Exception ex) {
        // Default to failing fast
        if (LOG.isDebugEnabled()) {
            LOG.debug("Unable to verify action class [#0]", ex, className);
        }
        throw new ConfigurationException(ex, loc);
    }
    return true;
}

From source file:com.alibaba.fastjson.parser.ParserConfig.java

public ObjectDeserializer createJavaBeanDeserializer(Class<?> clazz, Type type) {
    boolean asmEnable = this.asmEnable & !this.fieldBased;
    if (asmEnable) {
        JSONType jsonType = TypeUtils.getAnnotation(clazz, JSONType.class);

        if (jsonType != null) {
            Class<?> deserializerClass = jsonType.deserializer();
            if (deserializerClass != Void.class) {
                try {
                    Object deseralizer = deserializerClass.newInstance();
                    if (deseralizer instanceof ObjectDeserializer) {
                        return (ObjectDeserializer) deseralizer;
                    }//from  www. j  a v  a 2 s  . co m
                } catch (Throwable e) {
                    // skip
                }
            }

            asmEnable = jsonType.asm();
        }

        if (asmEnable) {
            Class<?> superClass = JavaBeanInfo.getBuilderClass(clazz, jsonType);
            if (superClass == null) {
                superClass = clazz;
            }

            for (;;) {
                if (!Modifier.isPublic(superClass.getModifiers())) {
                    asmEnable = false;
                    break;
                }

                superClass = superClass.getSuperclass();
                if (superClass == Object.class || superClass == null) {
                    break;
                }
            }
        }
    }

    if (clazz.getTypeParameters().length != 0) {
        asmEnable = false;
    }

    if (asmEnable && asmFactory != null && asmFactory.classLoader.isExternalClass(clazz)) {
        asmEnable = false;
    }

    if (asmEnable) {
        asmEnable = ASMUtils.checkName(clazz.getSimpleName());
    }

    if (asmEnable) {
        if (clazz.isInterface()) {
            asmEnable = false;
        }
        JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);

        if (asmEnable && beanInfo.fields.length > 200) {
            asmEnable = false;
        }

        Constructor<?> defaultConstructor = beanInfo.defaultConstructor;
        if (asmEnable && defaultConstructor == null && !clazz.isInterface()) {
            asmEnable = false;
        }

        for (FieldInfo fieldInfo : beanInfo.fields) {
            if (fieldInfo.getOnly) {
                asmEnable = false;
                break;
            }

            Class<?> fieldClass = fieldInfo.fieldClass;
            if (!Modifier.isPublic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }

            if (fieldClass.isMemberClass() && !Modifier.isStatic(fieldClass.getModifiers())) {
                asmEnable = false;
                break;
            }

            if (fieldInfo.getMember() != null //
                    && !ASMUtils.checkName(fieldInfo.getMember().getName())) {
                asmEnable = false;
                break;
            }

            JSONField annotation = fieldInfo.getAnnotation();
            if (annotation != null //
                    && ((!ASMUtils.checkName(annotation.name())) //
                            || annotation.format().length() != 0 //
                            || annotation.deserializeUsing() != Void.class //
                            || annotation.unwrapped())
                    || (fieldInfo.method != null && fieldInfo.method.getParameterTypes().length > 1)) {
                asmEnable = false;
                break;
            }

            if (fieldClass.isEnum()) { // EnumDeserializer
                ObjectDeserializer fieldDeser = this.getDeserializer(fieldClass);
                if (!(fieldDeser instanceof EnumDeserializer)) {
                    asmEnable = false;
                    break;
                }
            }
        }
    }

    if (asmEnable) {
        if (clazz.isMemberClass() && !Modifier.isStatic(clazz.getModifiers())) {
            asmEnable = false;
        }
    }

    if (!asmEnable) {
        return new JavaBeanDeserializer(this, clazz, type);
    }

    JavaBeanInfo beanInfo = JavaBeanInfo.build(clazz, type, propertyNamingStrategy);
    try {
        return asmFactory.createJavaBeanDeserializer(this, beanInfo);
        // } catch (VerifyError e) {
        // e.printStackTrace();
        // return new JavaBeanDeserializer(this, clazz, type);
    } catch (NoSuchMethodException ex) {
        return new JavaBeanDeserializer(this, clazz, type);
    } catch (JSONException asmError) {
        return new JavaBeanDeserializer(this, beanInfo);
    } catch (Exception e) {
        throw new JSONException("create asm deserializer error, " + clazz.getName(), e);
    }
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>/*from   w  ww.  ja  v  a2 s  .c om*/
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method. If no such method can
 * be found, return <code>null</code>.
 * </p>
 *
 * @param clazz
 *            The class of the object
 * @param method
 *            The method that we wish to call
 * @return The accessible method
 * @since 1.8.0
 */
public static Method getAccessibleMethod(Class<?> clazz, Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return null;
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return null;
    }

    boolean sameClass = true;
    if (clazz == null) {
        clazz = method.getDeclaringClass();
    } else {
        sameClass = clazz.equals(method.getDeclaringClass());
        if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName());
        }
    }

    // If the class is public, we are done
    if (Modifier.isPublic(clazz.getModifiers())) {
        if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            setMethodAccessible(method); // Default access superclass
            // workaround
        }
        return method;
    }

    final String methodName = method.getName();
    final Class<?>[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes);
    }

    return method;
}

From source file:com.rapidminer.tools.Tools.java

public static void findImplementationsInJar(ClassLoader loader, JarFile jar, Class<?> superClass,
        List<String> implementations) {
    Enumeration<JarEntry> e = jar.entries();
    while (e.hasMoreElements()) {
        JarEntry entry = e.nextElement();
        String name = entry.getName();
        int dotClass = name.lastIndexOf(".class");
        if (dotClass < 0) {
            continue;
        }//from w ww  . ja  v a2  s.c  o  m
        name = name.substring(0, dotClass);
        name = name.replaceAll("/", "\\.");
        try {
            Class<?> c = loader.loadClass(name);
            if (superClass.isAssignableFrom(c)) {
                if (!java.lang.reflect.Modifier.isAbstract(c.getModifiers())) {
                    implementations.add(name);
                }
            }
        } catch (Throwable t) {
        }
    }
}

From source file:org.springframework.core.annotation.AnnotationUtils.java

/**
 * Register the annotation-declared default values for the given attributes,
 * if available./*from   w  w w  . jav a2s.c  om*/
 * @param attributes the annotation attributes to process
 * @since 4.3.2
 */
public static void registerDefaultValues(AnnotationAttributes attributes) {
    // Only do defaults scanning for public annotations; we'd run into
    // IllegalAccessExceptions otherwise, and we don't want to mess with
    // accessibility in a SecurityManager environment.
    Class<? extends Annotation> annotationType = attributes.annotationType();
    if (annotationType != null && Modifier.isPublic(annotationType.getModifiers())) {
        // Check declared default values of attributes in the annotation type.
        for (Method annotationAttribute : getAttributeMethods(annotationType)) {
            String attributeName = annotationAttribute.getName();
            Object defaultValue = annotationAttribute.getDefaultValue();
            if (defaultValue != null && !attributes.containsKey(attributeName)) {
                if (defaultValue instanceof Annotation) {
                    defaultValue = getAnnotationAttributes((Annotation) defaultValue, false, true);
                } else if (defaultValue instanceof Annotation[]) {
                    Annotation[] realAnnotations = (Annotation[]) defaultValue;
                    AnnotationAttributes[] mappedAnnotations = new AnnotationAttributes[realAnnotations.length];
                    for (int i = 0; i < realAnnotations.length; i++) {
                        mappedAnnotations[i] = getAnnotationAttributes(realAnnotations[i], false, true);
                    }
                    defaultValue = mappedAnnotations;
                }
                attributes.put(attributeName, new DefaultValueHolder(defaultValue));
            }
        }
    }
}

From source file:org.gradle.api.internal.AbstractClassGenerator.java

private <T> Class<? extends T> generateUnderLock(Class<T> type) {
    Map<Class<?>, Class<?>> cache = GENERATED_CLASSES.get(getClass());
    if (cache == null) {
        // WeakHashMap won't work here. It keeps a strong reference to the mapping value, which is the generated class in this case
        // However, the generated class has a strong reference to the source class (by extending it), so the keys will always be
        // strongly reachable while this Class is strongly reachable. Use weak references for both key and value of the mapping instead.
        cache = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK);
        GENERATED_CLASSES.put(getClass(), cache);
    }//from  w ww. j  a v a 2s  .  c  o  m
    Class<?> generatedClass = cache.get(type);
    if (generatedClass != null) {
        return generatedClass.asSubclass(type);
    }

    if (Modifier.isPrivate(type.getModifiers())) {
        throw new GradleException(
                String.format("Cannot create a proxy class for private class '%s'.", type.getSimpleName()));
    }
    if (Modifier.isAbstract(type.getModifiers())) {
        throw new GradleException(
                String.format("Cannot create a proxy class for abstract class '%s'.", type.getSimpleName()));
    }

    Class<? extends T> subclass;
    try {
        ClassMetaData classMetaData = inspectType(type);

        ClassBuilder<T> builder = start(type, classMetaData);

        builder.startClass();

        if (!DynamicObjectAware.class.isAssignableFrom(type)) {
            if (ExtensionAware.class.isAssignableFrom(type)) {
                throw new UnsupportedOperationException(
                        "A type that implements ExtensionAware must currently also implement DynamicObjectAware.");
            }
            builder.mixInDynamicAware();
        }
        if (!GroovyObject.class.isAssignableFrom(type)) {
            builder.mixInGroovyObject();
        }
        builder.addDynamicMethods();
        if (classMetaData.conventionAware && !IConventionAware.class.isAssignableFrom(type)) {
            builder.mixInConventionAware();
        }

        Class noMappingClass = Object.class;
        for (Class<?> c = type; c != null && noMappingClass == Object.class; c = c.getSuperclass()) {
            if (c.getAnnotation(NoConventionMapping.class) != null) {
                noMappingClass = c;
            }
        }

        Set<PropertyMetaData> conventionProperties = new HashSet<PropertyMetaData>();

        for (PropertyMetaData property : classMetaData.properties.values()) {
            if (SKIP_PROPERTIES.contains(property.name)) {
                continue;
            }

            if (property.injector) {
                builder.addInjectorProperty(property);
                for (Method getter : property.getters) {
                    builder.applyServiceInjectionToGetter(property, getter);
                }
                for (Method setter : property.setters) {
                    builder.applyServiceInjectionToSetter(property, setter);
                }
                continue;
            }

            boolean needsConventionMapping = false;
            if (classMetaData.isExtensible()) {
                for (Method getter : property.getters) {
                    if (!Modifier.isFinal(getter.getModifiers())
                            && !getter.getDeclaringClass().isAssignableFrom(noMappingClass)) {
                        needsConventionMapping = true;
                        break;
                    }
                }
            }

            if (needsConventionMapping) {
                conventionProperties.add(property);
                builder.addConventionProperty(property);
                for (Method getter : property.getters) {
                    builder.applyConventionMappingToGetter(property, getter);
                }
            }

            if (needsConventionMapping) {
                for (Method setter : property.setters) {
                    if (!Modifier.isFinal(setter.getModifiers())) {
                        builder.applyConventionMappingToSetter(property, setter);
                    }
                }
            }
        }

        Set<Method> actionMethods = classMetaData.missingOverloads;
        for (Method method : actionMethods) {
            builder.addActionMethod(method);
        }

        // Adds a set method for each mutable property
        for (PropertyMetaData property : classMetaData.properties.values()) {
            if (property.setters.isEmpty()) {
                continue;
            }
            if (Iterable.class.isAssignableFrom(property.getType())) {
                // Currently not supported
                continue;
            }

            if (property.setMethods.isEmpty()) {
                for (Method setter : property.setters) {
                    builder.addSetMethod(property, setter);
                }
            } else if (conventionProperties.contains(property)) {
                for (Method setMethod : property.setMethods) {
                    builder.applyConventionMappingToSetMethod(property, setMethod);
                }
            }
        }

        for (Constructor<?> constructor : type.getConstructors()) {
            if (Modifier.isPublic(constructor.getModifiers())) {
                builder.addConstructor(constructor);
            }
        }

        subclass = builder.generate();
    } catch (Throwable e) {
        throw new GradleException(
                String.format("Could not generate a proxy class for class %s.", type.getName()), e);
    }

    cache.put(type, subclass);
    cache.put(subclass, subclass);
    return subclass;
}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

private TDefinitions createDefinitionsByThirdparty(final List<String> errors, Path defsPath) {
    TDefinitions defs = null;//  w  w w. ja  v a 2 s.  c  om
    try {
        Reflections reflections = new Reflections("org.eclipse.winery.repository.ext");
        Set<Class<? extends DefinitionGenerator>> implenmetions = reflections
                .getSubTypesOf(org.eclipse.winery.repository.ext.imports.custom.DefinitionGenerator.class);
        Iterator<Class<? extends DefinitionGenerator>> it = implenmetions.iterator();
        while (it.hasNext()) {
            Class<? extends DefinitionGenerator> impl = it.next();
            if (!Modifier.isAbstract(impl.getModifiers())) {
                DefinitionGenerator generator = impl.newInstance();
                if (generator.accept(defsPath)) {
                    try {
                        defs = generator.makeDefinitions(defsPath);
                    } catch (Exception e) {
                        CSARImporter.logger.error("error occurs while make defintions by: " + impl.toString());
                        continue;
                    }
                } else
                    CSARImporter.logger
                            .info(impl.toString() + " refuse to deal with file: " + defsPath.getFileName());
            }
        }

    } catch (Exception e) {
        errors.add("Could not parse definitions " + defsPath.getFileName() + " ");
        CSARImporter.logger.debug("parse error", e);
    }
    return defs;
}