Example usage for java.lang.reflect Modifier isPublic

List of usage examples for java.lang.reflect Modifier isPublic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPublic.

Prototype

public static boolean isPublic(int mod) 

Source Link

Document

Return true if the integer argument includes the public modifier, false otherwise.

Usage

From source file:org.apache.tomcat.util.mx.DynamicMBeanProxy.java

private void init() {
    if (methods != null)
        return;/*from w w  w  .  j  a  va  2s. c  o m*/
    methods = real.getClass().getMethods();
    for (int j = 0; j < methods.length; ++j) {
        String name = methods[j].getName();

        if (name.startsWith("get")) {
            if (methods[j].getParameterTypes().length != 0) {
                continue;
            }
            if (!Modifier.isPublic(methods[j].getModifiers())) {
                //log.debug("not public " + methods[j] );
                continue;
            }
            Class ret = methods[j].getReturnType();
            if (!supportedType(ret)) {
                if (log.isDebugEnabled())
                    log.debug("Unsupported " + ret);
                continue;
            }
            name = unCapitalize(name.substring(3));

            getAttMap.put(name, methods[j]);
            // just a marker, we don't use the value 
            attMap.put(name, methods[j]);
        } else if (name.startsWith("is")) {
            // not used in our code. Add later

        } else if (name.startsWith("set")) {
            Class params[] = methods[j].getParameterTypes();
            if (params.length != 1) {
                continue;
            }
            if (!Modifier.isPublic(methods[j].getModifiers()))
                continue;
            Class ret = params[0];
            if (!supportedType(ret)) {
                continue;
            }
            name = unCapitalize(name.substring(3));
            setAttMap.put(name, methods[j]);
            attMap.put(name, methods[j]);
        } else {
            if (methods[j].getParameterTypes().length != 0) {
                continue;
            }
            if (methods[j].getDeclaringClass() == Object.class)
                continue;
            if (!Modifier.isPublic(methods[j].getModifiers()))
                continue;
            invokeAttMap.put(name, methods[j]);
        }
    }
}

From source file:com.weibo.api.motan.core.extension.ExtensionLoader.java

private void checkConstructorPublic(Class<T> clz) {
    Constructor<?>[] constructors = clz.getConstructors();

    if (constructors == null || constructors.length == 0) {
        failThrows(clz, "Error has no public no-args constructor");
    }//  ww  w  . ja  va  2  s .  c o m

    for (Constructor<?> constructor : constructors) {
        if (Modifier.isPublic(constructor.getModifiers()) && constructor.getParameterTypes().length == 0) {
            return;
        }
    }

    failThrows(clz, "Error has no public no-args constructor");
}

From source file:fr.imag.model2roo.addon.graph.NodeEntityMetadata.java

private MethodMetadataBuilder getIdentifierMutator() {
    if (parent != null) {
        final MethodMetadataBuilder parentIdMutator = parent.getIdentifierMutator();
        if (parentIdMutator != null
                && parentIdMutator.getParameterTypes().get(0).getJavaType().equals(idType)) {
            return parentIdMutator;
        }/*from w  ww  .j av a2 s  . co m*/
    }

    JavaSymbolName requiredMutatorName = BeanInfoUtils.getMutatorMethodName(idField);

    final List<JavaType> parameterTypes = Arrays.asList(idField.getFieldType());
    final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName("id"));

    // See if the user provided the field
    if (!getId().equals(idField.getDeclaredByMetadataId())) {
        // Locate an existing mutator
        final MethodMetadata method = memberDetails.getMethod(requiredMutatorName, parameterTypes);
        if (method != null) {
            if (Modifier.isPublic(method.getModifier())) {
                // Method exists and is public so return it
                return new MethodMetadataBuilder(method);
            }

            // Method is not public so make the required mutator name unique
            requiredMutatorName = new JavaSymbolName(requiredMutatorName.getSymbolName() + "_");
        }
    }

    // We declared the field in this ITD, so produce a public mutator for it
    final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine("this." + idField.getFieldName().getSymbolName() + " = id;");

    return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, requiredMutatorName, JavaType.VOID_PRIMITIVE,
            AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder);
}

From source file:com.link_intersystems.lang.reflect.criteria.MemberCriteriaTest.java

@Test
public void publicMethods() {
    memberCriteria.membersOfType(Method.class);
    memberCriteria.withAccess(AccessType.PUBLIC);
    ClassCriteria classCriteria = new ClassCriteria();
    Iterable<Class<?>> classIterable = classCriteria.getIterable(ArrayList.class);
    Iterable<Member> memberIterable = memberCriteria.getIterable(classIterable);
    assertTrue(memberIterable.iterator().hasNext());
    for (Member member : memberIterable) {
        assertTrue("member must be a method", member instanceof Method);
        int modifiers = member.getModifiers();
        assertTrue(Modifier.isPublic(modifiers));
        assertFalse(Modifier.isProtected(modifiers));
        assertFalse(Modifier.isPrivate(modifiers));
    }/*from  ww  w . j  ava2s .c om*/
}

From source file:kelly.util.BeanUtils.java

/**
 * Copy the property values of the given source bean into the given target bean.
 * <p>Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean//from   w  ww  .  j a  v a  2s  .c om
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void copyProperties(Object source, Object target, Class<?> editable,
        String... ignoreProperties) {

    Validate.notNull(source, "Source must not be null");
    Validate.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null
                        && writeMethod.getParameterTypes()[0].isAssignableFrom(readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    } catch (Throwable ex) {
                        throw new BeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:com.tmind.framework.pub.utils.MethodUtils.java

private static synchronized Method[] getPublicDeclaredMethods(Class clz) {
    // Looking up Class.getDeclaredMethods is relatively expensive,
    // so we cache the results.
    final Class fclz = clz;
    Method[] result = (Method[]) declaredMethodCache.get(fclz);
    if (result != null) {
        return result;
    }/* ww w  . j av a  2  s . c  om*/

    // We have to raise privilege for getDeclaredMethods
    result = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            try {

                return fclz.getDeclaredMethods();

            } catch (SecurityException ex) {
                // this means we're in a limited security environment
                // so let's try going through the public methods
                // and null those those that are not from the declaring
                // class
                Method[] methods = fclz.getMethods();
                for (int i = 0, size = methods.length; i < size; i++) {
                    Method method = methods[i];
                    if (!(fclz.equals(method.getDeclaringClass()))) {
                        methods[i] = null;
                    }
                }
                return methods;
            }
        }
    });

    // Null out any non-public methods.
    for (int i = 0; i < result.length; i++) {
        Method method = result[i];
        if (method != null) {
            int mods = method.getModifiers();
            if (!Modifier.isPublic(mods)) {
                result[i] = null;
            }
        }
    }

    // Add it to the cache.
    declaredMethodCache.put(clz, result);
    return result;
}

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 w w .  ja  v  a 2s  .co  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.batoo.jpa.common.reflect.ReflectHelper.java

/**
 * Returns the property descriptors for the class.
 * /*from w  w  w  . j  a v  a  2s.c  o m*/
 * @param clazz
 *            the class
 * @return the property descriptors
 * 
 * @since $version
 * @author hceylan
 */
public static PropertyDescriptor[] getProperties(Class<?> clazz) {
    final List<PropertyDescriptor> properties = Lists.newArrayList();

    final Method[] methodList = clazz.getDeclaredMethods();

    // check each method.
    for (final Method method : methodList) {
        if (method == null) {
            continue;
        }

        // skip static and private methods.
        final int mods = method.getModifiers();
        if (Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
            continue;
        }

        final String name = method.getName();

        if (method.getParameterTypes().length == 0) {
            if (name.startsWith(ReflectHelper.GET_PREFIX)) {
                properties.add(new PropertyDescriptor(clazz, name.substring(3), method));
            } else if ((method.getReturnType() == boolean.class) && name.startsWith(ReflectHelper.IS_PREFIX)) {
                properties.add(new PropertyDescriptor(clazz, name.substring(2), method));
            }
        }
    }

    return properties.toArray(new PropertyDescriptor[properties.size()]);
}

From source file:org.eclipse.buildship.docs.source.SourceMetaDataVisitor.java

private int extractModifiers(GroovySourceAST t, AbstractLanguageElement metaData) {
    final int modifiers = extractModifiers(t);
    metaData.setAbstract(Modifier.isAbstract(modifiers));
    if (groovy) {
        metaData.setPublic(!Modifier.isProtected(modifiers) && !Modifier.isPrivate(modifiers));
    } else {/*  w w w  .  j ava2 s  .  c  o m*/
        metaData.setPublic(Modifier.isPublic(modifiers) || (metaData instanceof MethodMetaData
                && ((MethodMetaData) metaData).getOwnerClass().isInterface()));
    }
    return modifiers;
}

From source file:microsoft.exchange.webservices.data.core.service.schema.ServiceObjectSchema.java

/**
 * Adds the schema property names to dictionary.
 *
 * @param type                   The type.
 * @param propertyNameDictionary The property name dictionary.
 *//*w ww  .  j a v a  2  s  . c  o  m*/
protected static void addSchemaPropertyNamesToDictionary(Class<?> type,
        Map<PropertyDefinition, String> propertyNameDictionary) {

    Field[] fields = type.getDeclaredFields();
    for (Field field : fields) {
        int modifier = field.getModifiers();
        if (Modifier.isPublic(modifier) && Modifier.isStatic(modifier)) {
            Object o;
            try {
                o = field.get(null);
                if (o instanceof PropertyDefinition) {
                    PropertyDefinition propertyDefinition = (PropertyDefinition) o;
                    propertyNameDictionary.put(propertyDefinition, field.getName());
                }
            } catch (IllegalArgumentException e) {
                LOG.error(e);

                // Skip the field
            } catch (IllegalAccessException e) {
                LOG.error(e);

                // Skip the field
            }
        }
    }
}