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:bboss.org.apache.velocity.util.introspection.ClassMap.java

/**
 * Populate the Map of direct hits. These
 * are taken from all the public methods
 * that our class, its parents and their implemented interfaces provide.
 *///from   w  w  w  .  j  a v  a2  s .c  o m
private MethodCache createMethodCache() {
    MethodCache methodCache = new MethodCache(log);
    //
    // Looks through all elements in the class hierarchy. This one is bottom-first (i.e. we start
    // with the actual declaring class and its interfaces and then move up (superclass etc.) until we
    // hit java.lang.Object. That is important because it will give us the methods of the declaring class
    // which might in turn be abstract further up the tree.
    //
    // We also ignore all SecurityExceptions that might happen due to SecurityManager restrictions (prominently 
    // hit with Tomcat 5.5).
    //
    // We can also omit all that complicated getPublic, getAccessible and upcast logic that the class map had up
    // until Velocity 1.4. As we always reflect all elements of the tree (that's what we have a cache for), we will
    // hit the public elements sooner or later because we reflect all the public elements anyway.
    //
    // Ah, the miracles of Java for(;;) ... 
    for (Class classToReflect = getCachedClass(); classToReflect != null; classToReflect = classToReflect
            .getSuperclass()) {
        if (Modifier.isPublic(classToReflect.getModifiers())) {
            populateMethodCacheWith(methodCache, classToReflect);
        }
        Class[] interfaces = classToReflect.getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {
            populateMethodCacheWithInterface(methodCache, interfaces[i]);
        }
    }
    // return the already initialized cache
    return methodCache;
}

From source file:org.apache.axis2.transport.http.AbstractAgent.java

private void examineMethods(Method[] aDeclaredMethods) {
    for (int i = 0; i < aDeclaredMethods.length; i++) {
        Method method = aDeclaredMethods[i];

        Class[] parameterTypes = method.getParameterTypes();
        if ((Modifier.isProtected(method.getModifiers()) || Modifier.isPublic(method.getModifiers()))
                && method.getName().startsWith(METHOD_PREFIX) && parameterTypes.length == 2
                && parameterTypes[0].equals(HttpServletRequest.class)
                && parameterTypes[1].equals(HttpServletResponse.class)) {

            String key = method.getName().substring(METHOD_PREFIX.length()).toLowerCase();

            // ensure we don't overwrite existing method with superclass method
            if (!operationCache.containsKey(key)) {
                operationCache.put(key, method);
            }//from www .  ja  v a 2  s. c o m
        }
    }
}

From source file:org.jboss.dashboard.ui.config.components.factory.FactoryComponentFormatter.java

protected void serviceProperties(Component component) {
    Set properties = new TreeSet();
    if (component.getScope().equals(Component.SCOPE_GLOBAL)
            || component.getScope().equals(Component.SCOPE_VOLATILE)) {
        Object obj = null;//  w w  w  . j ava 2 s .  com
        try {
            obj = component.getObject();
        } catch (LookupException e) {
            log.error("Error: ", e);
        }

        if (obj instanceof Map) {
            properties.addAll(((Map) obj).keySet());
        } else if (obj instanceof List) {
            for (int i = 0; i < ((List) obj).size(); i++) {
                properties.add(new Integer(i));
            }
        } else {
            Method[] methods = obj.getClass().getMethods();
            for (int i = 0; i < methods.length; i++) {
                Method method = methods[i];
                String propertyName = getPropertyName(method);
                if (propertyName != null && isGetter(method))
                    properties.add(propertyName);
            }
            Field[] fields = obj.getClass().getFields();
            for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
                    properties.add(field.getName());
                }
            }
        }
        if (!properties.isEmpty()) {
            String propertyType = "";
            String fullPropertyType = "";
            renderFragment("propertiesStart");
            int indexStyle = 0;
            for (Iterator it = properties.iterator(); it.hasNext();) {
                indexStyle++;
                Object property = it.next();
                Object value = null;
                if (obj instanceof Map) {
                    value = ((Map) obj).get(property);
                    propertyType = "String";
                    fullPropertyType = "java.lang.String []";
                } else if (obj instanceof List) {
                    value = ((List) obj).get(((Integer) property).intValue());
                    propertyType = "String";
                    fullPropertyType = "java.lang.String []";
                } else {
                    String propertyName = (String) property;
                    // Find a getter.
                    String propertyAccessorSuffix = Character.toUpperCase(propertyName.charAt(0))
                            + (propertyName.length() > 1 ? propertyName.substring(1) : "");
                    String getterName = "get" + propertyAccessorSuffix;
                    String booleanGetterName = "is" + propertyAccessorSuffix;
                    Method getter = null;
                    Class propertyClass = null;
                    try {
                        getter = obj.getClass().getMethod(getterName, new Class[0]);
                        if (getter != null)
                            try {
                                value = getter.invoke(obj, new Object[0]);
                                propertyClass = getter.getReturnType();
                            } catch (IllegalAccessException e) {
                                log.error("Error:", e);
                            } catch (InvocationTargetException e) {
                                log.error("Error:", e);
                            }
                    } catch (NoSuchMethodException e) {
                        log.debug("No getter " + getterName + " found.");
                        try {
                            getter = obj.getClass().getMethod(booleanGetterName, new Class[0]);
                            if (getter != null)
                                try {
                                    value = getter.invoke(obj, new Object[0]);
                                    propertyClass = getter.getReturnType();
                                } catch (IllegalAccessException iae) {
                                    log.error("Error:", iae);
                                } catch (InvocationTargetException ite) {
                                    log.error("Error:", ite);
                                }
                        } catch (NoSuchMethodException e1) {
                            log.debug("No getter " + booleanGetterName + " found.");
                        }
                    }

                    if (propertyClass == null) {
                        //Find field
                        try {
                            Field field = obj.getClass().getField(propertyName);
                            if (field != null) {
                                value = field.get(obj);
                                propertyClass = field.getType();
                            }
                        } catch (NoSuchFieldException e) {
                            log.error("Error: ", e);
                        } catch (IllegalAccessException e) {
                            log.error("Error: ", e);
                        }
                    }

                    if (propertyClass.isArray()) {
                        String componentTypeClass = propertyClass.getComponentType().getName();
                        if (componentTypeClass.indexOf('.') != -1) {
                            propertyType = componentTypeClass.substring(componentTypeClass.lastIndexOf('.') + 1)
                                    + "[]";
                        } else {
                            propertyType = componentTypeClass + " []";
                        }
                        fullPropertyType = componentTypeClass + " []";
                    } else if (propertyClass.isPrimitive()) {
                        propertyType = propertyClass.getName();
                        fullPropertyType = propertyType;
                    } else {
                        if (propertyClass.getName().indexOf('.') != -1) {
                            propertyType = propertyClass.getName()
                                    .substring(propertyClass.getName().lastIndexOf('.') + 1);
                        } else {
                            propertyType = propertyClass.getName();
                        }
                        fullPropertyType = propertyClass.getName();
                    }
                }

                if (value == null) {
                    value = "";
                } else if (value instanceof String || value instanceof Integer || value instanceof Short
                        || value instanceof Character || value instanceof Long || value instanceof Byte
                        || value instanceof Boolean || value instanceof Float || value instanceof Double
                        || value.getClass().isPrimitive()) {

                } else if (value.getClass().isArray()) {
                    int length = Array.getLength(value);
                    String componentType = value.getClass().getComponentType().getName();
                    value = componentType + " [" + length + "]";
                } else {
                    value = value.getClass().getName();
                }

                Map configuredValues = component.getComponentConfiguredProperties();
                List configuredValue = (List) configuredValues.get(property);
                StringBuffer sb = new StringBuffer();
                if (configuredValue != null)
                    for (int i = 0; i < configuredValue.size(); i++) {
                        PropertyChangeProcessingInstruction instruction = (PropertyChangeProcessingInstruction) configuredValue
                                .get(i);
                        if (instruction instanceof PropertyAddProcessingInstruction) {
                            sb.append("\n+").append(instruction.getPropertyValue());
                        } else if (instruction instanceof PropertySubstractProcessingInstruction) {
                            sb.append("\n-").append(instruction.getPropertyValue());
                        } else if (instruction instanceof PropertySetProcessingInstruction) {
                            sb.setLength(0);
                            sb.append(" ").append(instruction.getPropertyValue());
                        }
                    }

                setAttribute("configuredValue", StringUtils.replace(sb.toString(), ",", ", "));
                setAttribute("propertyType", propertyType);
                setAttribute("fullPropertyType", fullPropertyType);
                setAttribute("propertyName", property);
                setAttribute("propertyValue", value);
                setAttribute("estilo", indexStyle % 2 == 0 ? "skn-even_row" : "skn-odd_row");
                renderFragment("outputProperty");
            }
            renderFragment("propertiesEnd");
        }
    }
}

From source file:com.sun.socialsite.business.impl.JPAListenerManagerImpl.java

/**
 * Calls any appropriately-annotated methods in listeners which
 * have registered to receive lifecycle events for a class to
 * which the specified entity belongs./*w ww  . j a  va  2  s. c o  m*/
 * @param entity the entity experiencing a lifecycle event.
 * @param annotationClass the annotation class corresponding to the event.
 */
private static void notifyListeners(Object entity, Class<? extends Annotation> annotationClass) {

    //log.trace(String.format("notifyListeners(%s, %s)", entity, annotationClass.getCanonicalName()));

    Collection<Object> listeners = getListeners(entity);
    for (Object listener : listeners) {
        Method[] methods = listener.getClass().getMethods();
        for (int i = 0; i < methods.length; i++) {
            Method method = methods[i];
            if (method.getAnnotation(annotationClass) != null) {
                try {
                    log.debug(String.format("calling %s.%s(%s)", listener, method.getName(), entity));
                    // Handle cases where the listener is a nested class
                    if (Modifier.isPublic(method.getModifiers()))
                        method.setAccessible(true);
                    method.invoke(listener, entity);
                } catch (Throwable t) {
                    // TODO: Catch and Handle individual Exception types
                    log.error("Exception", t);
                }
            }
        }
    }
}

From source file:net.groupbuy.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target, String[] ignoreProperties) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }/*from w  w  w  .  jav a2 s.c  o  m*/
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.flipkart.polyguice.dropwiz.PolyguiceApp.java

private Object createResource(Class<?> cls, T config, Environment env) throws InstantiationException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    LOGGER.debug("creating object of type {}", cls);
    try {/*w w w .  j  av a  2s .c om*/
        Constructor<?> ctor = cls.getConstructor(Configuration.class, Environment.class);
        int mod = ctor.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) {
            LOGGER.debug("using ctor {}", ctor.toGenericString());
            return ctor.newInstance(config, env);
        }
    } catch (NoSuchMethodException exep) {
        //NOOP, not even log
    }

    try {
        Constructor<?> ctor = cls.getConstructor(Environment.class, Configuration.class);
        int mod = ctor.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) {
            LOGGER.debug("using ctor {}", ctor.toGenericString());
            return ctor.newInstance(env, config);
        }
    } catch (NoSuchMethodException exep) {
        //NOOP, not even log
    }

    try {
        Constructor<?> ctor = cls.getConstructor(Configuration.class);
        int mod = ctor.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) {
            LOGGER.debug("using ctor {}", ctor.toGenericString());
            return ctor.newInstance(config);
        }
    } catch (NoSuchMethodException exep) {
        //NOOP, not even log
    }

    try {
        Constructor<?> ctor = cls.getConstructor(Environment.class);
        int mod = ctor.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) {
            LOGGER.debug("using ctor {}", ctor.toGenericString());
            return ctor.newInstance(env);
        }
    } catch (NoSuchMethodException exep) {
        //NOOP, not even log
    }

    try {
        Constructor<?> ctor = cls.getConstructor();
        int mod = ctor.getModifiers();
        if (Modifier.isPublic(mod) && !Modifier.isAbstract(mod)) {
            LOGGER.debug("using ctor {}", ctor.toGenericString());
            return ctor.newInstance();
        }
    } catch (NoSuchMethodException exep) {
        //NOOP, not even log
    }
    return null;
}

From source file:tools.xor.util.ClassUtil.java

/** 
 * Invoke the given method as a privileged action, if necessary. 
 * @param target the object on which the method needs to be invoked
 * @param field we are reading or writing
 * @param value to set in the field//from   www .  j  a  va  2 s.c om
 * @param read true if this a read operation
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
public static Object invokeFieldAsPrivileged(final Object target, final Field field, final Object value,
        final boolean read) throws InvocationTargetException, IllegalAccessException {

    if (Modifier.isPublic(field.getModifiers())) {
        Object readValue = null;
        if (read)
            readValue = field.get(target);
        else
            field.set(target, value);
        return readValue;
    } else {
        return AccessController.doPrivileged(new PrivilegedAction<Object>() {
            public Object run() {
                field.setAccessible(true);
                Object readValue = null;
                try {
                    if (read)
                        readValue = field.get(target);
                    else
                        field.set(target, value);
                } catch (Exception e) {
                    throw wrapRun(e);
                }
                return readValue;
            }
        });
    }
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

@SuppressWarnings("checkstyle:JavadocMethod")
public void listMethods(final RoutingContext routingContext) {
    String microserviceName = routingContext.request().getParam("microservice");
    Bean bean = gatewayRegistry.get(microserviceName);

    if (bean == null) {
        routingContext.response().setStatusCode(503).end("Resource not available");
    } else {//from   w ww.  j  ava  2s . c om
        JsonArray methods = new JsonArray();

        for (final Method m : bean.getBeanClass().getDeclaredMethods()) {
            if (Modifier.isPublic(m.getModifiers())) {
                JsonObject method = new JsonObject();
                method.put("methodName", m.getName());
                JsonArray params = new JsonArray();
                for (Class c : m.getParameterTypes()) {
                    params.add(c.getName());
                }
                method.put("parameters", params);
                method.put("returns", m.getReturnType().getName());

                methods.add(method);
            }
        }

        routingContext.response().end(methods.encodePrettily());
    }
}

From source file:org.codehaus.groovy.grails.commons.metaclass.BaseApiProvider.java

private boolean isNotExcluded(Method method, final int modifiers) {
    final String name = method.getName();

    if (EXCLUDED_METHODS.contains(name))
        return false;

    boolean isStatic = Modifier.isStatic(modifiers);

    // skip plain setters/getters by default for instance methods (non-static)
    if (!isStatic && (GrailsClassUtils.isSetter(name, method.getParameterTypes())
            || GrailsClassUtils.isGetter(name, method.getParameterTypes()))) {
        return false;
    }/*  w  ww  .  j a va2  s .  c o  m*/

    int minParameters = isStatic ? 0 : 1;

    return Modifier.isPublic(modifiers) && !(method.isSynthetic() || method.isBridge())
            && !Modifier.isAbstract(modifiers) && !name.contains("$")
            && (method.getParameterTypes().length >= minParameters);
}

From source file:com.icfcc.cache.interceptor.AbstractFallbackCacheOperationSource.java

private Collection<CacheOperation> computeCacheOperations(Method method, Class<?> targetClass) {
    // Don't allow no-public methods as required.
    if (allowPublicMethodsOnly() && !Modifier.isPublic(method.getModifiers())) {
        return null;
    }//from ww w  .  ja va 2  s  . c  o  m

    // The method may be on an interface, but we need attributes from the target class.
    // If the target class is null, the method will be unchanged.
    Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    // If we are dealing with method with generic parameters, find the original method.
    specificMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);

    // First try is the method in the target class.
    Collection<CacheOperation> opDef = findCacheOperations(specificMethod);
    if (opDef != null) {
        return opDef;
    }

    // Second try is the caching operation on the target class.
    opDef = findCacheOperations(specificMethod.getDeclaringClass());
    if (opDef != null) {
        return opDef;
    }

    if (specificMethod != method) {
        // Fall back is to look at the original method.
        opDef = findCacheOperations(method);
        if (opDef != null) {
            return opDef;
        }
        // Last fall back is the class of the original method.
        return findCacheOperations(method.getDeclaringClass());
    }
    return null;
}