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.eclipse.wb.internal.core.databinding.ui.editor.contentproviders.ChooseClassUiContentProvider.java

/**
 * This method calculate state and sets or clear error message. Subclasses maybe override this
 * method for observe special states./*  w  ww .  j a  v a2 s.  c om*/
 */
protected void calculateFinish() {
    String className = getClassName();
    // route events
    if (m_router != null) {
        m_router.handle();
    }
    // check state
    if (className.length() == 0) {
        // empty class
        setErrorMessage(m_configuration.getEmptyClassErrorMessage());
    } else {
        // check clear of default value (maybe not class)
        if (m_configuration.isDefaultString(className) || className.equals(m_configuration.getClearValue())
                || ArrayUtils.indexOf(m_configuration.getDefaultValues(), className) != -1) {
            setErrorMessage(null);
            return;
        }
        // check load class
        Class<?>[][] constructorsParameters = m_configuration.getConstructorsParameters();
        String errorMessagePrefix = m_configuration.getErrorMessagePrefix();
        //
        boolean noConstructor = false;
        try {
            Class<?> testClass = loadClass(className);
            // check permissions
            int modifiers = testClass.getModifiers();
            if (!Modifier.isPublic(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotPublic);
                return;
            }
            if (!m_configuration.isChooseInterfaces() && Modifier.isAbstract(modifiers)) {
                setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateAbstract);
                return;
            }
            // check constructor
            if (m_checkClasses) {
                m_checkClasses = false;
                if (constructorsParameters != null) {
                    for (int i = 0; i < constructorsParameters.length; i++) {
                        Class<?>[] constructorParameters = constructorsParameters[i];
                        for (int j = 0; j < constructorParameters.length; j++) {
                            Class<?> constructorParameterClass = constructorParameters[j];
                            if (constructorParameterClass.isArray()) {
                                String parameterClassName = constructorParameterClass.getComponentType()
                                        .getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = Array
                                            .newInstance(loadClass(parameterClassName), new int[1]).getClass();
                                }
                            } else {
                                String parameterClassName = constructorParameterClass.getName();
                                if (parameterClassName.startsWith("org.eclipse")) {
                                    constructorParameters[j] = loadClass(parameterClassName);
                                }
                            }
                        }
                    }
                }
            }
            if (constructorsParameters != null) {
                noConstructor = true;
                for (int i = 0; i < constructorsParameters.length; i++) {
                    try {
                        testClass.getConstructor(constructorsParameters[i]);
                        noConstructor = false;
                        break;
                    } catch (SecurityException e) {
                    } catch (NoSuchMethodException e) {
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            setErrorMessage(errorMessagePrefix + Messages.ChooseClassUiContentProvider_validateNotExist);
            return;
        }
        // prepare error message for constructor
        if (noConstructor) {
            StringBuffer parameters = new StringBuffer(errorMessagePrefix);
            parameters.append(Messages.ChooseClassUiContentProvider_validatePublicConstructor);
            for (int i = 0; i < constructorsParameters.length; i++) {
                Class<?>[] constructorParameters = constructorsParameters[i];
                if (i > 0) {
                    parameters.append(" ");
                }
                parameters.append(ClassUtils.getShortClassName(className));
                parameters.append("(");
                for (int j = 0; j < constructorParameters.length; j++) {
                    if (j > 0) {
                        parameters.append(", ");
                    }
                    parameters.append(ClassUtils.getShortClassName(constructorParameters[j]));
                }
                parameters.append(")");
            }
            parameters.append(".");
            setErrorMessage(parameters.toString());
        } else {
            setErrorMessage(null);
        }
    }
}

From source file:net.mojodna.sprout.Sprout.java

public final void setBeanFactory(final BeanFactory factory) throws BeansException {
    if (!factory.isSingleton(beanName)) {
        log.warn(getClass().getName() + " must be defined with singleton=\"true\" in order to self-register.");
        return;/*w  w w  .j  a v a  2 s.co  m*/
    }

    final String pkgName = getClass().getPackage().getName();
    final String path = pkgName.substring(pkgName.indexOf(PACKAGE_DELIMITER) + PACKAGE_DELIMITER.length())
            .replace('.', '/') + "/";

    if (factory instanceof AbstractBeanFactory) {
        final AbstractBeanFactory dlbf = (AbstractBeanFactory) factory;

        final Collection<Method> methods = SproutUtils.getDeclaredMethods(getClass(), Sprout.class);

        // register beans for each url
        log.debug("Registering paths...");
        for (final Iterator<Method> i = methods.iterator(); i.hasNext();) {
            final Method method = i.next();
            String name = method.getName();
            if (Modifier.isPublic(method.getModifiers())
                    && method.getReturnType().equals(ActionForward.class)) {
                if (name.equals("publick"))
                    name = "public";
                final String url = path + name.replaceAll("([A-Z])", "_$1").toLowerCase();
                log.debug(url);
                if (!ArrayUtils.contains(dlbf.getAliases(beanName), url))
                    dlbf.registerAlias(beanName, url);
            }
        }
    } else {
        log.warn("Unable to self-register; factory bean was of an unsupported type.");
        throw new BeanNotOfRequiredTypeException(beanName, AbstractBeanFactory.class, factory.getClass());
    }
}

From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java

private static Collection<String> getPropertyNames(Collection<Method> methods) {
    Collection<String> methodNames = new ArrayList<String>();

    /*/* w w  w.ja v a2s. c  o  m*/
     * If a method is an instance method, does not return void, takes no parameters 
     * and is named "get..." (it's assumed to be public), add the corresponding field name.
     */
    for (Method method : methods) {
        assert Modifier.isPublic(method.getModifiers()) : method;
        String methodName = method.getName();
        Matcher getterNameMatcher = GETTER_PREFIX.matcher(methodName);

        if (!Modifier.isStatic(method.getModifiers()) && (method.getReturnType() != Void.class)
                && (method.getParameterTypes().length == 0) && getterNameMatcher.matches()) {

            // the first group is the (uppercase) first letter of the field name
            methodNames.add(getterNameMatcher.replaceFirst(getterNameMatcher.group(1).toLowerCase() + "$2"));
        }

    }

    return methodNames;
}

From source file:org.alfresco.module.org_alfresco_module_rm.api.PublicAPITestUtil.java

/**
 * Check if the supplied {@link Executable#getModifiers() modifiers} indicate that an extension can access the
 * element. Here we assume that an extension can see public and protected items, but not package protected (or
 * private)./*from  w  w w .  j  a  va  2s .  c  o m*/
 *
 * @param modifiers The java language modifiers.
 * @return {@code true} if the item is visible to an extension.
 */
private static boolean isVisibleToExtender(int modifiers) {
    return Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers);
}

From source file:objenome.util.bytecode.SgUtils.java

/**
 * Checks if the modifiers are valid for a method. If any of the modifiers
 * is not valid an <code>IllegalArgumentException</code> is thrown.
 * // www. j a v  a2  s. c  o  m
 * @param modifiers
 *            Modifiers.
 */
// CHECKSTYLE:OFF Cyclomatic complexity is OK
public static void checkMethodModifiers(int modifiers) {

    // Base check
    checkModifiers(METHOD, modifiers);

    // Check overlapping modifiers
    if (Modifier.isPrivate(modifiers)) {
        if (Modifier.isProtected(modifiers) || Modifier.isPublic(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }
    if (Modifier.isProtected(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isPublic(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }
    if (Modifier.isPublic(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isProtected(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ACCESS_MODIFIER_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }

    // Check illegal abstract modifiers
    if (Modifier.isAbstract(modifiers)) {
        if (Modifier.isPrivate(modifiers) || Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)
                || Modifier.isNative(modifiers) || Modifier.isStrict(modifiers)
                || Modifier.isSynchronized(modifiers)) {
            throw new IllegalArgumentException(
                    METHOD_ILLEGAL_ABSTRACT_MODIFIERS_ERROR + " [" + Modifier.toString(modifiers) + ']');
        }
    }

    // Check native and strictfp
    if (Modifier.isNative(modifiers) && Modifier.isStrict(modifiers)) {
        throw new IllegalArgumentException(
                METHOD_NATIVE_STRICTFP_ERROR + " [" + Modifier.toString(modifiers) + ']');
    }

}

From source file:org.grails.datastore.mapping.reflect.ClassPropertyFetcher.java

private void processField(Field field) {
    if (field.isSynthetic()) {
        return;// ww w.j  a  va  2 s  .  co m
    }
    final int modifiers = field.getModifiers();
    final String name = field.getName();
    if (!Modifier.isPublic(modifiers)) {
        if (name.indexOf('$') == -1) {
            fieldsByName.put(name, field);
        }
    } else {
        if (name.indexOf('$') == -1) {
            boolean staticField = Modifier.isStatic(modifiers);
            if (staticField) {
                List<PropertyFetcher> propertyFetchers = staticFetchers.get(name);
                if (propertyFetchers == null) {
                    staticFetchers.put(name, propertyFetchers = new ArrayList<PropertyFetcher>());
                }
                propertyFetchers.add(new FieldReaderFetcher(field, staticField));
            } else {
                instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
            }
        }
    }
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatementTest.java

@Test
public void testConfirmPackageLevel() throws Exception {

    Method m = AClassWithPLMethod.class.getDeclaredMethod("foo");
    assertFalse(Modifier.isPrivate(m.getModifiers()));
    assertFalse(Modifier.isPublic(m.getModifiers()));
    assertFalse(Modifier.isProtected(m.getModifiers()));
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

public static boolean canBeFunctionalMocked(Type type) {

    Class<?> rawClass = new GenericClass(type).getRawClass();
    final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

    if (Properties.hasTargetClassBeenLoaded() && (rawClass.equals(targetClass))) {
        return false;
    }//from   w  w w  .  j  a  v  a 2s  .  c o m

    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName())
            || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive()
            || rawClass.isAnonymousClass() || rawClass.isEnum() ||
            //note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
            !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }

    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
        if a class has not been instrumented (eg because belonging to javax.*),
        then if it is final we cannot mock it :(
        recall that instrumentation does remove the final modifiers
         */
        return false;
    }

    //FIXME: tmp fix to avoid mocking any class with package access methods
    try {
        for (Method m : rawClass.getDeclaredMethods()) {

            /*
            Unfortunately, it does not seem there is a "isPackageLevel" method, so we have
            to go by exclusion
             */

            if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())
                    && !Modifier.isPrivate(m.getModifiers()) && !m.isBridge() && !m.isSynthetic()
                    && !m.getName().equals(ClassResetter.STATIC_RESET)) {
                return false;
            }
        }
    } catch (NoClassDefFoundError | Exception e) {
        //this could happen if we failed to load the class
        AtMostOnceLogger.warn(logger,
                "Failed to check if can mock class " + rawClass.getName() + ": " + e.getMessage());
        return false;
    }

    //avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }

    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        //avoid weird cases like java.lang.Appendable
        return false;
    }

    //ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList(
    //add here if needed
    );

    if (avoid.contains(rawClass)) {
        return false;
    }

    return true;
}

From source file:org.hibernate.internal.util.ReflectHelper.java

/**
 * Is this member publicly accessible./*  w ww  .  j  a v a2  s . co  m*/
 *
 * @param clazz The class which defines the member
 * @param member The memeber.
 * @return True if the member is publicly accessible, false otherwise.
 */
public static boolean isPublic(Class clazz, Member member) {
    return Modifier.isPublic(member.getModifiers()) && Modifier.isPublic(clazz.getModifiers());
}

From source file:com.google.code.siren4j.util.ReflectionUtils.java

/**
 * Determine if the method is a getter./*from  w  w w  .java2  s .  co m*/
 *
 * @param method
 * @return
 */
public static boolean isGetter(Method method) {
    String name = method.getName();
    String[] splitname = StringUtils.splitByCharacterTypeCamelCase(name);
    return !method.getReturnType().equals(void.class) && Modifier.isPublic(method.getModifiers())
            && (splitname[0].equals(GETTER_PREFIX_BOOLEAN) || splitname[0].equals(GETTER_PREFIX));
}