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:ch.rasc.extclassgenerator.ModelGenerator.java

public static ModelBean createModel(final Class<?> clazz, final OutputConfig outputConfig) {

    Assert.notNull(clazz, "clazz must not be null");
    Assert.notNull(outputConfig.getIncludeValidation(), "includeValidation must not be null");

    ModelCacheKey key = new ModelCacheKey(clazz.getName(), outputConfig);
    SoftReference<ModelBean> modelReference = modelCache.get(key);
    if (modelReference != null && modelReference.get() != null) {
        return modelReference.get();
    }//  w  w  w .ja v a  2s .  c  om

    Model modelAnnotation = clazz.getAnnotation(Model.class);

    final ModelBean model = new ModelBean();

    if (modelAnnotation != null && StringUtils.hasText(modelAnnotation.value())) {
        model.setName(modelAnnotation.value());
    } else {
        model.setName(clazz.getName());
    }

    if (modelAnnotation != null) {
        model.setAutodetectTypes(modelAnnotation.autodetectTypes());
    }

    if (modelAnnotation != null) {
        model.setExtend(modelAnnotation.extend());
        model.setIdProperty(modelAnnotation.idProperty());
        model.setVersionProperty(trimToNull(modelAnnotation.versionProperty()));
        model.setPaging(modelAnnotation.paging());
        model.setDisablePagingParameters(modelAnnotation.disablePagingParameters());
        model.setCreateMethod(trimToNull(modelAnnotation.createMethod()));
        model.setReadMethod(trimToNull(modelAnnotation.readMethod()));
        model.setUpdateMethod(trimToNull(modelAnnotation.updateMethod()));
        model.setDestroyMethod(trimToNull(modelAnnotation.destroyMethod()));
        model.setMessageProperty(trimToNull(modelAnnotation.messageProperty()));
        model.setWriter(trimToNull(modelAnnotation.writer()));
        model.setReader(trimToNull(modelAnnotation.reader()));
        model.setSuccessProperty(trimToNull(modelAnnotation.successProperty()));
        model.setTotalProperty(trimToNull(modelAnnotation.totalProperty()));
        model.setRootProperty(trimToNull(modelAnnotation.rootProperty()));
        model.setWriteAllFields(modelAnnotation.writeAllFields());
        model.setIdentifier(trimToNull(modelAnnotation.identifier()));
        String clientIdProperty = trimToNull(modelAnnotation.clientIdProperty());
        if (StringUtils.hasText(clientIdProperty)) {
            model.setClientIdProperty(clientIdProperty);
            model.setClientIdPropertyAddToWriter(true);
        } else {
            model.setClientIdProperty(null);
            model.setClientIdPropertyAddToWriter(false);
        }
    }

    final Set<String> hasReadMethod = new HashSet<String>();

    BeanInfo bi;
    try {
        bi = Introspector.getBeanInfo(clazz);
    } catch (IntrospectionException e) {
        throw new RuntimeException(e);
    }

    for (PropertyDescriptor pd : bi.getPropertyDescriptors()) {
        if (pd.getReadMethod() != null && pd.getReadMethod().getAnnotation(JsonIgnore.class) == null) {
            hasReadMethod.add(pd.getName());
        }
    }

    if (clazz.isInterface()) {
        final List<Method> methods = new ArrayList<Method>();

        ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
            @Override
            public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                methods.add(method);
            }
        });

        Collections.sort(methods, new Comparator<Method>() {
            @Override
            public int compare(Method o1, Method o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });

        for (Method method : methods) {
            createModelBean(model, method, outputConfig);
        }
    } else {

        final Set<String> fields = new HashSet<String>();

        Set<ModelField> modelFieldsOnType = AnnotationUtils.getRepeatableAnnotation(clazz, ModelFields.class,
                ModelField.class);
        for (ModelField modelField : modelFieldsOnType) {
            if (StringUtils.hasText(modelField.value())) {
                ModelFieldBean modelFieldBean;

                if (StringUtils.hasText(modelField.customType())) {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.customType());
                } else {
                    modelFieldBean = new ModelFieldBean(modelField.value(), modelField.type());
                }

                updateModelFieldBean(modelFieldBean, modelField);
                model.addField(modelFieldBean);
            }
        }

        Set<ModelAssociation> modelAssociationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelAssociations.class, ModelAssociation.class);
        for (ModelAssociation modelAssociationAnnotation : modelAssociationsOnType) {
            AbstractAssociation modelAssociation = AbstractAssociation
                    .createAssociation(modelAssociationAnnotation);
            if (modelAssociation != null) {
                model.addAssociation(modelAssociation);
            }
        }

        Set<ModelValidation> modelValidationsOnType = AnnotationUtils.getRepeatableAnnotation(clazz,
                ModelValidations.class, ModelValidation.class);
        for (ModelValidation modelValidationAnnotation : modelValidationsOnType) {
            AbstractValidation modelValidation = AbstractValidation.createValidation(
                    modelValidationAnnotation.propertyName(), modelValidationAnnotation,
                    outputConfig.getIncludeValidation());
            if (modelValidation != null) {
                model.addValidation(modelValidation);
            }
        }

        ReflectionUtils.doWithFields(clazz, new FieldCallback() {

            @Override
            public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
                if (!fields.contains(field.getName()) && (field.getAnnotation(ModelField.class) != null
                        || field.getAnnotation(ModelAssociation.class) != null
                        || (Modifier.isPublic(field.getModifiers()) || hasReadMethod.contains(field.getName()))
                                && field.getAnnotation(JsonIgnore.class) == null)) {

                    // ignore superclass declarations of fields already
                    // found in a subclass
                    fields.add(field.getName());
                    createModelBean(model, field, outputConfig);

                }
            }

        });
    }

    modelCache.put(key, new SoftReference<ModelBean>(model));
    return model;
}

From source file:com.liferay.cli.support.util.ReflectionUtils.java

/**
 * Make the given constructor accessible, explicitly setting it accessible
 * if necessary. The <code>setAccessible(true)</code> method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).//from w  ww.  ja  v  a  2 s . c  om
 * 
 * @param ctor the constructor to make accessible
 * @see java.lang.reflect.Constructor#setAccessible
 */
public static void makeAccessible(final Constructor<?> ctor) {
    if (!Modifier.isPublic(ctor.getModifiers())
            || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers())) {
        ctor.setAccessible(true);
    }
}

From source file:com.glaf.core.util.ReflectUtils.java

public static Object getFieldValue(Object object, String fieldName) {
    try {//w w  w .  j  a  va  2  s . c o m
        Field field = ReflectionUtils.findField(object.getClass(), fieldName);
        if (!Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
        return ReflectionUtils.getField(field, object);
    } catch (Exception ex) {
        try {
            return BeanUtils.getProperty(object, fieldName);
        } catch (Exception e) {
        }
    }
    return null;
}

From source file:com.snaplogic.snaps.firstdata.Create.java

static boolean isGetter(Method method) {
    if (Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0) {
        String methodName = method.getName();
        if (methodName.matches(GET_REGEX) && !method.getReturnType().equals(void.class))
            return true;
        if (methodName.matches(IS_REGEX) && method.getReturnType().equals(boolean.class))
            return true;
    }//from   w  w w .j a va 2 s. c om
    return false;
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Determine whether the method is declared public static
 * @param m/*from ww  w  . ja v  a 2  s  .c  om*/
 * @return True if the method is declared public static
 */
public static boolean isPublicStatic(Method m) {
    final int modifiers = m.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
}

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   w ww.  j  ava2 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:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Determine whether the field is declared public static
 * @param f//from w  w w . j  a va 2 s  .com
 * @return True if the field is declared public static
 */
public static boolean isPublicStatic(Field f) {
    final int modifiers = f.getModifiers();
    return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
}

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

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified method, by scanning through
 * all implemented interfaces and subinterfaces.  If no such method
 * can be found, return <code>null</code>.</p>
 *
 * <p> There isn't any good reason why this method must be private.
 * It is because there doesn't seem any reason why other classes should
 * call this rather than the higher level methods.</p>
 *
 * @param clazz Parent class for the interfaces to be checked
 * @param methodName Method name of the method we wish to call
 * @param parameterTypes The parameter type signatures
 *///from ww w  . j  a va  2s .  c  o  m
private static Method getAccessibleMethodFromInterfaceNest(Class clazz, String methodName,
        Class parameterTypes[]) {

    Method method = null;

    // Search up the superclass chain
    for (; clazz != null; clazz = clazz.getSuperclass()) {

        // Check the implemented interfaces of the parent class
        Class interfaces[] = clazz.getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {

            // Is this interface public?
            if (!Modifier.isPublic(interfaces[i].getModifiers()))
                continue;

            // Does the method exist on this interface?
            try {
                method = interfaces[i].getDeclaredMethod(methodName, parameterTypes);
            } catch (NoSuchMethodException e) {
                ;
            }
            if (method != null)
                break;

            // Recursively check our parent interfaces
            method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes);
            if (method != null)
                break;

        }

    }

    // If we found a method return it
    if (method != null)
        return (method);

    // We did not find anything
    return (null);

}

From source file:org.evosuite.testcase.ImportsTestCodeVisitor.java

/** {@inheritDoc} */
@Override//from  w  w w  .  ja va2 s . co m
public void visitFieldStatement(FieldStatement statement) {
    Throwable exception = getException(statement);

    VariableReference retval = statement.getReturnValue();
    GenericField field = statement.getField();

    getClassName(retval);

    if (!field.isStatic()) {
        VariableReference source = statement.getSource();
        getClassName(source);
    } else {
        getClassName(field.getField().getDeclaringClass());
    }
    if (exception != null) {
        Class<?> ex = exception.getClass();
        while (!Modifier.isPublic(ex.getModifiers()))
            ex = ex.getSuperclass();
        getClassName(ex);
    }
    visitAssertions(statement);
}

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");
        }/*from w  ww .  j a  v  a  2s. com*/
        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;
}