Example usage for java.lang.reflect Method getModifiers

List of usage examples for java.lang.reflect Method getModifiers

Introduction

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

Prototype

@Override
public int getModifiers() 

Source Link

Usage

From source file:com.paladin.mvc.ActionServlet.java

/**
 * ???{method}/* w  w  w  .ja v a  2s  . com*/
 *
 * @param _action
 * @param _method
 * @return
 */
private Method getActionMethod(final Object _action, final String _method) {
    String key = _action.getClass().getSimpleName() + '.' + _method;
    Method m = methods.get(key);
    if (m != null)
        return m;
    for (Method method : _action.getClass().getMethods()) {
        if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(_method)) {
            synchronized (methods) {
                methods.put(key, method);
            }
            return method;
        }
    }
    return null;
}

From source file:de.hybris.platform.webservices.util.objectgraphtransformer.impl.AbstractNodeConfig.java

/**
 * Creates a lookup map containing all properties of passed type.
 * <p/>// w  w  w .  j av a2  s  . co  m
 * Result maps a property name to a {@link PropertyConfig}.
 * </p>
 * Any property which keeps java bean standard is found and used for {@link PropertyConfig} creation. For finding all
 * properties {@link Introspector} is used which returns general {@link PropertyDescriptor}. But read- and write
 * methods provided by {@link PropertyDescriptor} are only used as "suggestion" here and are getting post-processed
 * to assure following criteria:
 * <p/>
 * - no bridge or synthetic methods are allowed <br/>
 * - co-variant return types are handled correctly <br/>
 * 
 * @param type
 * @return
 */
private Map<String, PropertyConfig> createPropertiesFor(Class<?> type) {
    final Map<String, PropertyConfig> result = new TreeMap<String, PropertyConfig>();
    final Set<String> done = new HashSet<String>();
    while (type != null) {
        // we are only interested in declared methods (no bridge/synthetic ones)
        final Method[] methods = type.getDeclaredMethods();
        for (final Method method : methods) {
            // only public, non-bridged methods are of interest
            if (!method.isBridge() && Modifier.isPublic(method.getModifiers())) {
                // potential bean-getter property?
                if (method.getParameterTypes().length == 0 && method.getReturnType() != void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);

                        final Matcher matcher = BEAN_GETTER.matcher(methodName);
                        String propertyName = null;
                        if (matcher.matches()) {
                            propertyName = matcher.group(1);
                        } else {
                            if (method.getReturnType().equals(boolean.class)) {
                                final Matcher matcher2 = BEAN_BOOLEAN_GETTER.matcher(methodName);
                                if (matcher2.matches()) {
                                    propertyName = matcher2.group(1);
                                }
                            }
                        }

                        if (propertyName != null) {
                            propertyName = normalizePropertyName(propertyName);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setReadMethod(method);
                        }
                    }
                }

                // potential bean-setter property?
                if (method.getParameterTypes().length == 1 && method.getReturnType() == void.class) {
                    // not processed yet?
                    final String methodName = method.getName();
                    if (!done.contains(methodName)) {
                        done.add(methodName);
                        final Matcher setter = BEAN_SETTER.matcher(methodName);
                        if (setter.matches()) {
                            String propertyName = setter.group(1);
                            propertyName = Character.toLowerCase(propertyName.charAt(0))
                                    + propertyName.substring(1);

                            // get or create a PropertyConfig
                            DefaultPropertyConfig pCfg = (DefaultPropertyConfig) result.get(propertyName);
                            if (pCfg == null) {
                                pCfg = new DefaultPropertyConfig(propertyName, null, null);
                                result.put(propertyName, pCfg);
                            }
                            pCfg.setWriteMethod(method);
                        }
                    }
                }
            }

        }
        type = type.getSuperclass();
    }
    return result;
}

From source file:in.hatimi.nosh.support.CommandExecutor.java

private Method findMainMethod() {
    Method[] methods = cmdCls.getMethods();
    for (Method method : methods) {
        if (!method.getName().equals("execute")) {
            continue; //method name must be 'execute'
        }//  w w w. j a v  a 2  s.  c o m
        int mod = method.getModifiers();
        if (Modifier.isAbstract(mod)) {
            continue; //method cannot be abstract.
        }
        if (Modifier.isStatic(mod)) {
            continue; //method cannot be static.
        }
        if (Modifier.isSynchronized(mod)) {
            continue; //method cannot be synthetic.
        }
        if (!Modifier.isPublic(mod)) {
            continue; //method must be public.
        }
        if (method.getReturnType() != Void.TYPE) {
            continue; //method must not return a value.
        }
        Class<?>[] paramTypes = method.getParameterTypes();
        if (paramTypes.length > 1) {
            continue; //method can take at most one parameter.
        }
        if (paramTypes.length == 1 && !paramTypes[0].equals(String[].class)) {
            continue; //if single parameter, must be String[]
        }
        return method;
    }
    return null;
}

From source file:com.tmall.wireless.tangram3.support.SimpleClickSupport.java

private void findClickMethods(Method[] methods) {
    for (Method method : methods) {
        String methodName = method.getName();
        if (isValidMethodName(methodName)) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 3 || parameterTypes.length == 4) {
                    Class<?> viewType = parameterTypes[0];
                    Class<?> cellType = parameterTypes[1];
                    Class<?> clickIntType = parameterTypes[2];
                    if (View.class.isAssignableFrom(viewType) && BaseCell.class.isAssignableFrom(cellType)
                            && (clickIntType.equals(int.class) || clickIntType.equals(Integer.class))) {
                        if (parameterTypes.length == 4) {
                            Class<?> clickParamsType = parameterTypes[3];
                            if (Map.class.isAssignableFrom(clickParamsType)) {
                                mOnClickMethods.put(viewType, new OnClickMethod(4, method));
                            }//from  ww  w . j av a 2s  .c  o m
                        } else {
                            mOnClickMethods.put(viewType, new OnClickMethod(3, method));
                        }
                    }
                }
            }
        }
    }
}

From source file:kenh.xscript.elements.Debug.java

private void list(JList c) {
    if (result == null)
        return;//w  w  w. j  a  v  a 2 s  .  c  o  m

    if (StringUtils.isBlank(c.getSelectedValue().toString()))
        return;

    if (this.getEnvironment() != null) {

        String context = "";
        try {
            Object obj = this.getEnvironment().getVariable(c.getSelectedValue().toString());
            if (obj != null) {

                context = c.getSelectedValue().toString() + LINE_SEP + LINE_SEP;

                context += "-- Class: " + obj.getClass().getCanonicalName() + LINE_SEP;

                context += LINE_SEP;
                context += "-- Fields: " + LINE_SEP;
                Field[] fields = obj.getClass().getFields();

                for (Field field : fields) {
                    int i = field.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        context += "\t" + field.getName() + " - " + retval + LINE_SEP;
                    }
                }

                context += LINE_SEP;
                context += "-- Method: " + LINE_SEP;
                java.lang.reflect.Method[] methods = obj.getClass().getMethods();

                for (java.lang.reflect.Method method : methods) {
                    int i = method.getModifiers();
                    String retval = Modifier.toString(i);
                    if (StringUtils.contains(retval, "public")) {
                        Class[] pcs = method.getParameterTypes();
                        StringBuffer sb = new StringBuffer();

                        for (Class c_ : pcs) {
                            String s = c_.getSimpleName();
                            sb.append(s + ", ");
                        }

                        String p = StringUtils.trimToEmpty(StringUtils.substringBeforeLast(sb.toString(), ","));

                        context += "\t" + method.getName() + "(" + p + ") - " + retval + LINE_SEP;
                    }
                }

            } else {
                context = "<null>";
            }
        } catch (Exception e) {
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw);
            e.printStackTrace(pw);
            context = sw.toString();
        }

        result.setText(context);

    } else {
        result.setText(c.getSelectedValue().toString());
    }

    result.setCaretPosition(0);
    c.requestFocus();
}

From source file:org.hswebframework.web.cache.spring.fix.FixUseSupperClassFallbackCacheOperationSource.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 w  w  w  .  j av  a 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.
    // @CacheConfig?
    Collection<CacheOperation> opDef = findCacheOperations(targetClass, specificMethod);
    if (opDef != null) {
        return opDef;
    }

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

    if (specificMethod != method) {
        // Fallback is to look at the original method.
        opDef = findCacheOperations(targetClass, method);
        if (opDef != null) {
            return opDef;
        }
        // Last fallback is the class of the original method.
        opDef = findCacheOperations(method.getDeclaringClass());
        if (opDef != null && ClassUtils.isUserLevelMethod(method)) {
            return opDef;
        }
    }

    return null;
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

private boolean isPrimaryKey(Method method) {
    return isPublic(method.getModifiers())
            && (method.getAnnotation(Id.class) != null || method.getAnnotation(EmbeddedId.class) != null);
}

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

/**
 * <p>Find an accessible method that matches the given name and has compatible parameters.
 * Compatible parameters mean that every method parameter is assignable from
 * the given parameters./*from  w  w w.ja  va  2 s  . c  om*/
 * In other words, it finds a method with the given name
 * that will take the parameters given.<p>
 *
 * <p>This method is slightly undeterminstic since it loops
 * through methods names and return the first matching method.</p>
 *
 * <p>This method is used by
 * {@link
 * #invokeMethod(Object object,String methodName,Object [] args,Class[] parameterTypes)}.
 *
 * <p>This method can match primitive parameter by passing in wrapper classes.
 * For example, a <code>Boolean</code> will match a primitive <code>boolean</code>
 * parameter.
 *
 * @param clazz find method in this class
 * @param methodName find method with this name
 * @param parameterTypes find method with compatible parameters
 */
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
    // trace logging
    if (log.isTraceEnabled()) {
        log.trace("Matching name=" + methodName + " on " + clazz);
    }
    MethodDescriptor md = new MethodDescriptor(clazz, methodName, parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {
        // Check the cache first
        Method method = (Method) cache.get(md);
        if (method != null) {
            return method;
        }

        method = clazz.getMethod(methodName, parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + method);
            log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
        }

        try {
            //
            // XXX Default access superclass workaround
            //
            // When a public class has a default access superclass
            // with public methods, these methods are accessible.
            // Calling them from compiled code works fine.
            //
            // Unfortunately, using reflection to invoke these methods
            // seems to (wrongly) to prevent access even when the method
            // modifer is public.
            //
            // The following workaround solves the problem but will only
            // work from sufficiently privilages code.
            //
            // Better workarounds would be greatfully accepted.
            //
            method.setAccessible(true);

        } catch (SecurityException se) {
            // log but continue just in case the method.invoke works anyway
            if (!loggedAccessibleWarning) {
                boolean vunerableJVM = false;
                try {
                    String specVersion = System.getProperty("java.specification.version");
                    if (specVersion.charAt(0) == '1'
                            && (specVersion.charAt(0) == '0' || specVersion.charAt(0) == '1'
                                    || specVersion.charAt(0) == '2' || specVersion.charAt(0) == '3')) {

                        vunerableJVM = true;
                    }
                } catch (SecurityException e) {
                    // don't know - so display warning
                    vunerableJVM = true;
                }
                if (vunerableJVM) {
                    log.warn("Current Security Manager restricts use of workarounds for reflection bugs "
                            + " in pre-1.4 JVMs.");
                }
                loggedAccessibleWarning = true;
            }
            log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
        }
        cache.put(md, method);
        return method;

    } catch (NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods
    int paramSize = parameterTypes.length;
    Method[] methods = clazz.getMethods();
    for (int i = 0, size = methods.length; i < size; i++) {
        if (methods[i].getName().equals(methodName)) {
            // log some trace information
            if (log.isTraceEnabled()) {
                log.trace("Found matching name:");
                log.trace(methods[i]);
            }

            // compare parameters
            Class[] methodsParams = methods[i].getParameterTypes();
            int methodParamSize = methodsParams.length;
            if (methodParamSize == paramSize) {
                boolean match = true;
                for (int n = 0; n < methodParamSize; n++) {
                    if (log.isTraceEnabled()) {
                        log.trace("Param=" + parameterTypes[n].getName());
                        log.trace("Method=" + methodsParams[n].getName());
                    }
                    if (!isAssignmentCompatible(methodsParams[n], parameterTypes[n])) {
                        if (log.isTraceEnabled()) {
                            log.trace(methodsParams[n] + " is not assignable from " + parameterTypes[n]);
                        }
                        match = false;
                        break;
                    }
                }

                if (match) {
                    // get accessible version of method
                    Method method = getAccessibleMethod(methods[i]);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + methods[i]);
                        }
                        try {
                            //
                            // XXX Default access superclass workaround
                            // (See above for more details.)
                            //
                            method.setAccessible(true);

                        } catch (SecurityException se) {
                            // log but continue just in case the method.invoke works anyway
                            if (!loggedAccessibleWarning) {
                                log.warn(
                                        "Cannot use JVM pre-1.4 access bug workaround due to restrictive security manager.");
                                loggedAccessibleWarning = true;
                            }
                            log.debug(
                                    "Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
                                    se);
                        }
                        cache.put(md, method);
                        return method;
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }

    // didn't find a match
    log.trace("No match found.");
    return null;
}

From source file:org.jolokia.converter.json.BeanExtractor.java

private List<String> extractBeanAttributes(Object pValue) {
    List<String> attrs = new ArrayList<String>();
    for (Method method : pValue.getClass().getMethods()) {
        if (!Modifier.isStatic(method.getModifiers()) && !IGNORE_METHODS.contains(method.getName())
                && !isIgnoredType(method.getReturnType()) && !method.isAnnotationPresent(Transient.class)) {
            addAttributes(attrs, method);
        }/*from ww w .j a  va 2 s.c  o  m*/
    }
    return attrs;
}

From source file:net.famzangl.minecraft.minebot.ai.command.CommandRegistry.java

private void getCommandsForClass(Class<?> commandClass, List<CommandDefinition> commands) {
    for (final Method m : commandClass.getMethods()) {
        if (Modifier.isStatic(m.getModifiers()) && m.isAnnotationPresent(AICommandInvocation.class)) {
            LOGGER.debug(MARKER_REGISTER, "Registering method: %s#%s()", commandClass.getCanonicalName(),
                    m.getName());/*w  w w.  ja va 2s . c  o  m*/
            commands.addAll(getCommandsForMethod(m));
        }
    }
}