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:org.codehaus.groovy.grails.commons.DefaultGrailsControllerClass.java

private void methodStrategy(Collection<String> methodNames) {

    Class superClass = getClazz();

    while (superClass != null && superClass != Object.class && superClass != GroovyObject.class) {
        for (Method method : superClass.getMethods()) {
            if (Modifier.isPublic(method.getModifiers()) && method.getAnnotation(Action.class) != null) {
                String methodName = method.getName();

                if (!methodName.endsWith(FLOW_SUFFIX)) {
                    methodNames.add(methodName);
                    configureMappingForMethodAction(methodName);
                }/*  w  w  w.  jav  a2s.c  o m*/
            }
        }
        superClass = superClass.getSuperclass();
    }

    if (!isActionMethod(defaultActionName) && methodNames.size() == 1 && !isReadableProperty("scaffold")) {
        defaultActionName = methodNames.iterator().next();
    }
}

From source file:org.apache.poi.util.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.// w w w.j  a v  a  2s. c o  m
 * 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 
 * @return The accessible method
 */
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    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 {
        Method method = clazz.getMethod(methodName, parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + method);
            log.trace("isPublic:" + Modifier.isPublic(method.getModifiers()));
        }

        setMethodAccessible(method); // Default access superclass workaround

        return method;

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

    // search through all methods 
    int paramSize = parameterTypes.length;
    Method bestMatch = null;
    Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    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(clazz, methods[i]);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + methods[i]);
                        }
                        setMethodAccessible(method); // Default access superclass workaround
                        myCost = getTotalTransformationCost(parameterTypes, method.getParameterTypes());
                        if (myCost < bestMatchCost) {
                            bestMatch = method;
                            bestMatchCost = myCost;
                        }
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }
    if (bestMatch == null) {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

private void validateSetter(ModelSchemaExtractionContext<?> extractionContext, ModelType<?> propertyType,
        Method setter) {
    if (!Modifier.isAbstract(setter.getModifiers())) {
        throw invalidMethod(extractionContext, "non-abstract setters are not allowed", setter);
    }//from  w  ww.  jav  a2  s .co  m

    if (!setter.getReturnType().equals(void.class)) {
        throw invalidMethod(extractionContext, "setter method must have void return type", setter);
    }

    Type[] setterParameterTypes = setter.getGenericParameterTypes();
    if (setterParameterTypes.length != 1) {
        throw invalidMethod(extractionContext, "setter method must have exactly one parameter", setter);
    }

    ModelType<?> setterType = ModelType.paramType(setter, 0);
    if (!setterType.equals(propertyType)) {
        String message = "setter method param must be of exactly the same type as the getter returns (expected: "
                + propertyType + ", found: " + setterType + ")";
        throw invalidMethod(extractionContext, message, setter);
    }
}

From source file:javadz.beanutils.MethodUtils.java

/**
 * <p>Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method.  If no such method
 * can be found, return <code>null</code>.</p>
 *
 * @param clazz The class of the object/* w  w w  . j av  a  2 s.co  m*/
 * @param method The method that we wish to call
 * @return The accessible method
 * @since 1.8.0
 */
public static Method getAccessibleMethod(Class clazz, Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return (null);
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return (null);
    }

    boolean sameClass = true;
    if (clazz == null) {
        clazz = method.getDeclaringClass();
    } else {
        sameClass = clazz.equals(method.getDeclaringClass());
        if (!method.getDeclaringClass().isAssignableFrom(clazz)) {
            throw new IllegalArgumentException(
                    clazz.getName() + " is not assignable from " + method.getDeclaringClass().getName());
        }
    }

    // If the class is public, we are done
    if (Modifier.isPublic(clazz.getModifiers())) {
        if (!sameClass && !Modifier.isPublic(method.getDeclaringClass().getModifiers())) {
            setMethodAccessible(method); // Default access superclass workaround
        }
        return (method);
    }

    String methodName = method.getName();
    Class[] parameterTypes = method.getParameterTypes();

    // Check the implemented interfaces and subinterfaces
    method = getAccessibleMethodFromInterfaceNest(clazz, methodName, parameterTypes);

    // Check the superclass chain
    if (method == null) {
        method = getAccessibleMethodFromSuperclass(clazz, methodName, parameterTypes);
    }

    return (method);

}

From source file:com.liuguangqiang.permissionhelper.PermissionHelper.java

/**
 * Invoke a method with annotation PermissionDenied.
 *
 * @param obj//w  w w  .  j  av  a 2  s  .co m
 * @param permission
 */
private void invokeDeniedMethod(Object obj, String permission) {
    Class clazz = obj.getClass();
    PermissionDenied permissionDenied;

    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(PermissionDenied.class)) {
            permissionDenied = method.getAnnotation(PermissionDenied.class);
            if (permissionDenied.permission().equals(permission)) {
                if (method.getModifiers() != Modifier.PUBLIC) {
                    throw new IllegalArgumentException(
                            String.format("Annotation method %s must be public.", method));
                }

                if (method.getParameterTypes().length > 0) {
                    throw new RuntimeException(String.format("Cannot execute non-void method %s.", method));
                }

                try {
                    method.invoke(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.apache.hadoop.fs.TestHarFileSystem.java

@Test
public void testInheritedMethodsImplemented() throws Exception {
    int errors = 0;
    for (Method m : FileSystem.class.getDeclaredMethods()) {
        if (Modifier.isStatic(m.getModifiers()) || Modifier.isPrivate(m.getModifiers())
                || Modifier.isFinal(m.getModifiers())) {
            continue;
        }/*from   ww w .ja v  a 2 s .  com*/

        try {
            MustNotImplement.class.getMethod(m.getName(), m.getParameterTypes());
            try {
                HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
                LOG.error("HarFileSystem MUST not implement " + m);
                errors++;
            } catch (NoSuchMethodException ex) {
                // Expected
            }
        } catch (NoSuchMethodException exc) {
            try {
                HarFileSystem.class.getDeclaredMethod(m.getName(), m.getParameterTypes());
            } catch (NoSuchMethodException exc2) {
                LOG.error("HarFileSystem MUST implement " + m);
                errors++;
            }
        }
    }
    assertTrue((errors + " methods were not overridden correctly - see log"), errors <= 0);
}

From source file:org.gradle.model.internal.manage.schema.extract.ManagedImplTypeSchemaExtractionStrategySupport.java

private void ensureNoProtectedOrPrivateMethods(ModelSchemaExtractionContext<?> extractionContext,
        Class<?> typeClass) {
    Class<?> superClass = typeClass.getSuperclass();
    if (superClass != null && !superClass.equals(Object.class)) {
        ensureNoProtectedOrPrivateMethods(extractionContext, superClass);
    }/*from   w w  w.  j av  a  2 s. c o m*/

    Iterable<Method> protectedAndPrivateMethods = Iterables
            .filter(Arrays.asList(typeClass.getDeclaredMethods()), new Predicate<Method>() {
                @Override
                public boolean apply(Method method) {
                    int modifiers = method.getModifiers();
                    return !method.isSynthetic()
                            && (Modifier.isProtected(modifiers) || Modifier.isPrivate(modifiers));
                }
            });

    if (!Iterables.isEmpty(protectedAndPrivateMethods)) {
        throw invalidMethods(extractionContext, "protected and private methods are not allowed",
                protectedAndPrivateMethods);
    }
}

From source file:com.liuguangqiang.permissionhelper.PermissionHelper.java

/**
 * Invoke a method with annotation PermissionGranted.
 *
 * @param obj/*w  w  w .j  av  a  2  s .  c  o m*/
 * @param permission
 */
private void invokeGrantedMethod(Object obj, String permission) {
    Class clazz = obj.getClass();
    PermissionGranted permissionGranted;

    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(PermissionGranted.class)) {
            permissionGranted = method.getAnnotation(PermissionGranted.class);
            if (permissionGranted.permission().equals(permission)) {
                if (method.getModifiers() != Modifier.PUBLIC) {
                    throw new IllegalArgumentException(
                            String.format("Annotation method %s must be public.", method));
                }

                if (method.getParameterTypes().length > 0) {
                    throw new RuntimeException(String.format("Cannot execute non-void method %s.", method));
                }

                try {
                    method.invoke(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:org.dhatim.javabean.factory.BasicFactoryDefinitionParser.java

/**
 * Creates a FactoryInstanceFactory object.
 *
 * @param factoryDefinition/*from   w  ww  .  j  a v  a  2s.  com*/
 * @param className
 * @param staticGetInstanceMethodDef
 * @param factoryMethodDef
 * @return
 * @throws ClassNotFoundException
 * @throws SecurityException
 * @throws NoSuchMethodException
 */
private Factory<?> createFactoryInstanceFactory(String factoryDefinition, String className,
        String staticGetInstanceMethodDef, String factoryMethodDef)
        throws ClassNotFoundException, SecurityException, NoSuchMethodException {
    Class<?> factoryClass = ClassUtil.forName(className, this.getClass());
    Method getInstanceMethod = factoryClass.getMethod(staticGetInstanceMethodDef);
    Class<?> factoryType = getInstanceMethod.getReturnType();
    Method factoryMethod = factoryType.getMethod(factoryMethodDef);

    if (!Modifier.isStatic(getInstanceMethod.getModifiers())) {
        throw new NoSuchMethodException("No static method with the name '" + staticGetInstanceMethodDef
                + "' can be found on the class '" + className + "'.");
    }

    return new FactoryInstanceFactory(factoryDefinition, getInstanceMethod, factoryMethod);
}

From source file:org.jbpm.formModeler.core.model.PojoDataHolder.java

private Set<DataFieldHolder> calculatePropertyNames() throws Exception {

    Class clazz = getHolderClass();

    if (clazz == null) {
        return null;
    }/*w  w  w  . j  a  v  a 2 s .  co m*/

    Set<DataFieldHolder> dataFieldHolders = new TreeSet<DataFieldHolder>();

    for (Field field : clazz.getDeclaredFields()) {

        if (isValidType(field.getType().getName())) {
            String capitalizedName = capitalize(field.getName());
            try {
                Method setter = clazz.getDeclaredMethod("set" + capitalizedName, field.getType());

                if (!setter.getReturnType().getName().equals("void")
                        && !Modifier.isPublic(setter.getModifiers()))
                    continue;

                Method getter;

                if (field.getType().equals(boolean.class))
                    getter = clazz.getDeclaredMethod("is" + capitalizedName);
                else
                    getter = clazz.getDeclaredMethod("get" + capitalizedName);

                if (!getter.getReturnType().equals(field.getType())
                        && !Modifier.isPublic(getter.getModifiers()))
                    continue;

                Type type = field.getGenericType();

                DataFieldHolder fieldHolder;

                if (type instanceof ParameterizedType) {
                    ParameterizedType generictype = (ParameterizedType) type;
                    Type[] arguments = generictype.getActualTypeArguments();
                    if (arguments == null || arguments.length > 1)
                        fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName());
                    else
                        fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName(),
                                ((Class<?>) arguments[0]).getName());
                } else {
                    fieldHolder = new DataFieldHolder(this, field.getName(), field.getType().getName());
                }

                dataFieldHolders.add(fieldHolder);

            } catch (Exception e) {
                getLogger().debug("Unable to generate field holder for '{}': {}", field.getName(), e);
            }
        }
    }

    return dataFieldHolders;
}