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: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 method to invoke/*  w ww  .j a v  a2 s .  c  o  m*/
 * @param args to the method
 * @return result of the invocation
 * @throws InvocationTargetException while invoking the method
 * @throws IllegalAccessException when accessing the meta data
 */
//public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object[] args) 
public static Object invokeMethodAsPrivileged(final Object target, final Method method, final Object... args)
        throws InvocationTargetException, IllegalAccessException {
    if (Modifier.isPublic(method.getModifiers()))
        if (args == null)
            return method.invoke(target);
        else
            return method.invoke(target, args);
    return AccessController.doPrivileged(new PrivilegedAction<Object>() {
        public Object run() {
            method.setAccessible(true);
            Object result = null;
            try {
                if (args == null)
                    result = method.invoke(target);
                else
                    result = method.invoke(target, args);
            } catch (Exception e) {
                throw wrapRun(e);
            }
            return result;
        }
    });
}

From source file:org.jenkinsci.plugins.ghprb.GhprbTestUtil.java

public static List<String> checkClassForGetters(Class<?> clazz) {
    Field[] fields = clazz.getDeclaredFields();
    List<Field> xmlFields = new ArrayList<Field>();
    List<String> errors = new ArrayList<String>();

    for (Field field : fields) {
        int modifiers = field.getModifiers();
        if (modifiers == (Modifier.PRIVATE) || modifiers == (Modifier.PRIVATE | Modifier.FINAL)) {
            xmlFields.add(field);//from  ww w .  jav a 2 s  .c  o  m
        }
    }

    for (Field field : xmlFields) {
        String getter = "get" + StringUtils.capitalize(field.getName());
        try {
            Method method = clazz.getDeclaredMethod(getter);
            int modifier = method.getModifiers();
            if (!Modifier.isPublic(modifier)) {
                errors.add(getter + " is not a public method");
            }
        } catch (Exception e) {
            String wrongGetter = "is" + StringUtils.capitalize(field.getName());
            try {
                clazz.getDeclaredMethod(wrongGetter);
                errors.add("Setter is using the wrong name, is " + wrongGetter + " and should be " + getter);
            } catch (Exception err) {
                errors.add("Missing " + getter);
            }
        }
    }
    return errors;
}

From source file:org.cruxframework.crux.core.ioc.IocContainerManager.java

/**
 * /*  ww  w .jav a2 s  .c  om*/
 * @param type
 * @param added
 * @param path
 * @param configurations
 */
private static void bindImplicityInjectionsForMethods(Class<?> type, Set<String> added, Set<String> path,
        Map<String, IocConfig<?>> configurations) {
    for (Method method : type.getDeclaredMethods()) {
        Inject inject = method.getAnnotation(Inject.class);
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (inject != null && !Modifier.isAbstract(method.getModifiers()) && parameterTypes != null
                && parameterTypes.length > 0) {
            if (!added.contains(method.toString())) {
                added.add(method.toString());
                for (int i = 0; i < parameterTypes.length; i++) {
                    Class<?> parameterType = parameterTypes[i];
                    if (isBindable(parameterType, false)) {
                        if (path.contains(parameterType.getCanonicalName())) {
                            throw new IoCException(
                                    "IoC Create Looping Error between classes [" + type.getCanonicalName()
                                            + "] and [" + parameterType.getCanonicalName() + "].");
                        }
                        Set<String> methodPath = new HashSet<String>();
                        methodPath.addAll(path);
                        methodPath.add(parameterType.getCanonicalName());
                        bindTypeImplicitly(parameterType, configurations);
                        bindImplicityInjectcions(parameterType, new HashSet<String>(), methodPath, false,
                                configurations);
                    }
                }
            }
        }
    }
}

From source file:org.echocat.jemoni.jmx.support.SpringUtils.java

@Nullable
private static Method getMethod(@Nullable Class<?> fromType, boolean expectedStatic, Class<?> returnType,
        @Nonnull String name, @Nullable Class<?>... parameterTypes) {
    final Method method;
    if (fromType != null) {
        try {//from w  w  w . j a  v a 2  s  .c  om
            method = fromType.getMethod(name, parameterTypes);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(
                    buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes), e);
        }
        final int modifiers = method.getModifiers();
        if ((expectedStatic && !isStatic(modifiers)) || (!expectedStatic && isStatic(modifiers))
                || !returnType.isAssignableFrom(method.getReturnType())) {
            throw new RuntimeException(
                    buildMessageFor(fromType, expectedStatic, returnType, name, parameterTypes));
        }
    } else {
        method = null;
    }
    return method;
}

From source file:org.eclipse.gemini.blueprint.config.internal.adapter.CustomListenerAdapterUtils.java

private static Map<Class<?>, List<Method>> doDetermineCustomMethods(final Class<?> target,
        final String methodName, final Class<?>[] possibleArgumentTypes, final boolean onlyPublic) {
    final Map<Class<?>, List<Method>> methods = new LinkedHashMap<Class<?>, List<Method>>(3);

    final boolean trace = log.isTraceEnabled();

    org.springframework.util.ReflectionUtils.doWithMethods(target,
            new org.springframework.util.ReflectionUtils.MethodCallback() {

                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    if (!method.isBridge() && methodName.equals(method.getName())) {
                        if (onlyPublic && !Modifier.isPublic(method.getModifiers())) {
                            if (trace)
                                log.trace("Only public methods are considered; ignoring " + method);
                            return;
                        }/*from w w  w.  j  a v a 2s. c  o m*/
                        // take a look at the variables
                        Class<?>[] args = method.getParameterTypes();

                        if (args != null) {
                            // Properties can be ignored
                            if (args.length == 1) {
                                addMethod(args[0], method, methods);
                            }
                            // or passed as Map, Dictionary
                            else if (args.length == 2) {
                                Class<?> propType = args[1];

                                for (int i = 0; i < possibleArgumentTypes.length; i++) {
                                    Class<?> clazz = possibleArgumentTypes[i];
                                    if (clazz.isAssignableFrom(propType)) {
                                        addMethod(args[0], method, methods);
                                    }
                                }
                            }
                        }
                    }
                }

                private void addMethod(Class<?> key, Method mt, Map<Class<?>, List<Method>> methods) {

                    if (trace)
                        log.trace("discovered custom method [" + mt.toString() + "] on " + target);

                    List<Method> mts = methods.get(key);
                    if (mts == null) {
                        mts = new ArrayList<Method>(2);
                        methods.put(key, mts);
                        org.springframework.util.ReflectionUtils.makeAccessible(mt);
                        mts.add(mt);
                        return;
                    }
                    // add a method only if there is still space
                    if (mts.size() == 1) {
                        Method m = mts.get(0);
                        if (m.getParameterTypes().length == mt.getParameterTypes().length) {
                            if (trace)
                                log.trace("Method w/ signature " + methodSignature(m)
                                        + " has been already discovered; ignoring it");
                        } else {
                            org.springframework.util.ReflectionUtils.makeAccessible(mt);
                            mts.add(mt);
                        }
                    }
                }

                private String methodSignature(Method m) {
                    StringBuilder sb = new StringBuilder();
                    int mod = m.getModifiers();
                    if (mod != 0) {
                        sb.append(Modifier.toString(mod) + " ");
                    }
                    sb.append(m.getReturnType() + " ");
                    sb.append(m.getName() + "(");
                    Class<?>[] params = m.getParameterTypes();
                    for (int j = 0; j < params.length; j++) {
                        sb.append(params[j]);
                        if (j < (params.length - 1))
                            sb.append(",");
                    }
                    sb.append(")");
                    return sb.toString();
                }
            });

    return methods;
}

From source file:de.micromata.genome.util.runtime.ClassUtils.java

/**
 * Returns all 'visible' methods for the given class. Visible methods are:
 *
 * - own methods (clazz.getDeclaredMethods()) - all public and protected methods from it's inheritance hierarchy
 *
 * @param clazz the Class//from w w  w.j ava  2  s  . c o m
 * @return set of visible methods for that class
 */
public static Set<Method> getAllVisibleMethods(final Class<?> clazz) {
    Set<Method> allMethods = new HashSet<>();
    allMethods.addAll(Arrays.asList(clazz.getMethods()));
    allMethods.addAll(Arrays.asList(clazz.getDeclaredMethods()));

    for (Object obj : ClassUtils.getAllSuperclasses(clazz)) {
        Class aClass = (Class) obj;
        for (Method method : aClass.getDeclaredMethods()) {
            if (Modifier.isProtected(method.getModifiers())) {
                allMethods.add(method);
            }
        }
    }
    return allMethods;
}

From source file:org.assertj.assertions.generator.util.ClassUtil.java

private static Set<Method> filterGetterMethods(Method[] methods) {
    Set<Method> getters = new TreeSet<Method>(GETTER_COMPARATOR);
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (isPublic(method.getModifiers()) && isNotDefinedInObjectClass(method) && isGetter(method)) {
            getters.add(method);// www  . j a v a2  s .c  o m
        }
    }
    return getters;
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Returns the set of property names which have both a getter and a setter
 * method and are annotated to be persisted through the {@link SPPersister}
 * classes.//w w w  .  j a v a  2 s . co m
 * 
 * @param objectUnderTest
 *            The object that contains the persistable properties we want to
 *            find.
 * @param includeTransient
 *            If true the properties marked as transient will also be
 *            included. If false only the properties that are persisted and
 *            not transient are returned.
 * @param includeConstructorMutators
 *            If true the properties that have getters but can only be set
 *            through a constructor due to being final will be included. If
 *            false the persisted properties provided must have a setter.
 */
public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient,
        boolean includeConstructorMutators) throws Exception {
    Set<String> getters = new HashSet<String>();
    Set<String> setters = new HashSet<String>();
    for (Method m : objectUnderTest.getClass().getMethods()) {
        if (m.getName().equals("getClass"))
            continue;

        //skip non-public methods as they are not visible for persisting anyways.
        if (!Modifier.isPublic(m.getModifiers()))
            continue;
        //skip static methods
        if (Modifier.isStatic(m.getModifiers()))
            continue;

        if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
            Class<?> parentClass = objectUnderTest.getClass();
            boolean accessor = false;
            boolean ignored = false;
            boolean isTransient = false;
            parentClass.getMethod(m.getName(), m.getParameterTypes());//test
            while (parentClass != null) {
                Method parentMethod;
                try {
                    parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    parentClass = parentClass.getSuperclass();
                    continue;
                }
                if (parentMethod.getAnnotation(Accessor.class) != null) {
                    accessor = true;
                    if (parentMethod.getAnnotation(Transient.class) != null) {
                        isTransient = true;
                    }
                    break;
                } else if (parentMethod.getAnnotation(NonProperty.class) != null
                        || parentMethod.getAnnotation(NonBound.class) != null) {
                    ignored = true;
                    break;
                }
                parentClass = parentClass.getSuperclass();
            }
            if (accessor) {
                if (includeTransient || !isTransient) {
                    if (m.getName().startsWith("get")) {
                        getters.add(m.getName().substring(3));
                    } else if (m.getName().startsWith("is")) {
                        getters.add(m.getName().substring(2));
                    }
                }
            } else if (ignored) {
                //ignored so skip
            } else {
                fail("The method " + m.getName() + " of " + objectUnderTest.toString()
                        + " is a getter that is not annotated "
                        + "to be an accessor or transient. The exiting annotations are "
                        + Arrays.toString(m.getAnnotations()));
            }
        } else if (m.getName().startsWith("set")) {
            if (m.getAnnotation(Mutator.class) != null) {
                if ((includeTransient || m.getAnnotation(Transient.class) == null)
                        && (includeConstructorMutators
                                || !m.getAnnotation(Mutator.class).constructorMutator())) {
                    setters.add(m.getName().substring(3));
                }
            } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) {
                //ignored so skip and pass
            } else {
                fail("The method " + m.getName() + " is a setter that is not annotated "
                        + "to be a mutator or transient.");
            }
        }
    }

    Set<String> beanNames = new HashSet<String>();
    for (String beanName : getters) {
        if (setters.contains(beanName)) {
            String firstLetter = new String(new char[] { beanName.charAt(0) });
            beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase()));
        }
    }
    return beanNames;
}

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./*from ww  w.  j  a  v a2  s  . co 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:org.codehaus.groovy.grails.commons.GrailsDomainConfigurationUtil.java

/**
 * Checks whether is property is configurational.
 *
 * @param descriptor The descriptor//from   w  w  w.  ja  va  2  s  .  c  o m
 * @return true if it is configurational
 */
public static boolean isNotConfigurational(PropertyDescriptor descriptor) {

    final String name = descriptor.getName();
    Method readMethod = descriptor.getReadMethod();
    Method writeMethod = descriptor.getWriteMethod();

    if ((readMethod != null && Modifier.isStatic(readMethod.getModifiers())
            || (writeMethod != null && Modifier.isStatic(writeMethod.getModifiers())))) {
        return false;
    }

    return !Errors.class.isAssignableFrom(descriptor.getPropertyType()) && isNotConfigurational(name);
}