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:guru.qas.martini.annotation.MartiniAnnotationCallback.java

protected void process(Method method, A annotation) {
    checkState(Modifier.isPublic(method.getModifiers()), "Method is not public: %s", method);

    String regex = getValue(annotation).trim();
    String annotationName = annotationClass.getSimpleName();
    checkState(!regex.isEmpty(), "@%s requires non-empty regex values.", annotationName);
    checkState(!regularExpressions.contains(regex), "Multiple methods found for @%s regex \"%s\"",
            annotationName, regex);/* ww  w. ja v a  2  s . c o  m*/
    Pattern pattern = Pattern.compile(regex);
    regularExpressions.add(regex);

    String name = String.format("%s%s", annotationName.toLowerCase(), atomicInteger.getAndIncrement());

    DefaultStep step = new DefaultStep(annotationName, pattern, method);
    beanFactory.registerSingleton(name, step);
}

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

private boolean isConstructorCallMethod(Method method) {
    return method != null && Modifier.isStatic(method.getModifiers())
            && Modifier.isPublic(method.getModifiers()) && method.getName().equals(CONSTRUCTOR_METHOD)
            && method.getParameterTypes().length > 0;
}

From source file:org.evosuite.testcase.statements.FunctionalMockStatement.java

public static boolean canBeFunctionalMocked(Type type) {

    Class<?> rawClass = new GenericClass(type).getRawClass();
    final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();

    if (Properties.hasTargetClassBeenLoaded() && (rawClass.equals(targetClass))) {
        return false;
    }/*  w w  w.  j  av a 2 s.c o  m*/

    if (EvoSuiteMock.class.isAssignableFrom(rawClass) || MockList.isAMockClass(rawClass.getName())
            || rawClass.equals(Class.class) || rawClass.isArray() || rawClass.isPrimitive()
            || rawClass.isAnonymousClass() || rawClass.isEnum() ||
            //note: Mockito can handle package-level classes, but we get all kinds of weird exceptions with instrumentation :(
            !Modifier.isPublic(rawClass.getModifiers())) {
        return false;
    }

    if (!InstrumentedClass.class.isAssignableFrom(rawClass) && Modifier.isFinal(rawClass.getModifiers())) {
        /*
        if a class has not been instrumented (eg because belonging to javax.*),
        then if it is final we cannot mock it :(
        recall that instrumentation does remove the final modifiers
         */
        return false;
    }

    //FIXME: tmp fix to avoid mocking any class with package access methods
    try {
        for (Method m : rawClass.getDeclaredMethods()) {

            /*
            Unfortunately, it does not seem there is a "isPackageLevel" method, so we have
            to go by exclusion
             */

            if (!Modifier.isPublic(m.getModifiers()) && !Modifier.isProtected(m.getModifiers())
                    && !Modifier.isPrivate(m.getModifiers()) && !m.isBridge() && !m.isSynthetic()
                    && !m.getName().equals(ClassResetter.STATIC_RESET)) {
                return false;
            }
        }
    } catch (NoClassDefFoundError | Exception e) {
        //this could happen if we failed to load the class
        AtMostOnceLogger.warn(logger,
                "Failed to check if can mock class " + rawClass.getName() + ": " + e.getMessage());
        return false;
    }

    //avoid cases of infinite recursions
    boolean onlySelfReturns = true;
    for (Method m : rawClass.getDeclaredMethods()) {
        if (!rawClass.equals(m.getReturnType())) {
            onlySelfReturns = false;
            break;
        }
    }

    if (onlySelfReturns && rawClass.getDeclaredMethods().length > 0) {
        //avoid weird cases like java.lang.Appendable
        return false;
    }

    //ad-hoc list of classes we should not really mock
    List<Class<?>> avoid = Arrays.asList(
    //add here if needed
    );

    if (avoid.contains(rawClass)) {
        return false;
    }

    return true;
}

From source file:gobblin.runtime.cli.PublicMethodsGobblinCliFactory.java

private boolean canUseMethod(Method method) {
    if (!Modifier.isPublic(method.getModifiers())) {
        return false;
    }/*from   w  ww.jav  a 2s  .c o m*/
    if (BLACKLISTED_FROM_CLI.contains(method.getName())) {
        return false;
    }
    if (method.isAnnotationPresent(NotOnCli.class)) {
        return false;
    }
    Class<?>[] parameters = method.getParameterTypes();
    if (parameters.length > 2) {
        return false;
    }
    if (parameters.length == 1 && parameters[0] != String.class) {
        return false;
    }
    return true;
}

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

public static boolean isBeanPropertyWriteMethod(Method method) {
    return method != null && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers()) && method.getDeclaringClass() != Object.class
            && method.getParameterTypes().length == 1 && method.getName().startsWith("set")
            && method.getName().length() > 3;
}

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

public static boolean isBeanPropertyReadMethod(Method method) {
    return method != null && Modifier.isPublic(method.getModifiers())
            && !Modifier.isStatic(method.getModifiers()) && method.getReturnType() != void.class
            && method.getDeclaringClass() != Object.class && method.getParameterTypes().length == 0
            && ((method.getName().startsWith("get") && method.getName().length() > 3)
                    || (method.getName().startsWith("is") && method.getName().length() > 2));
}

From source file:ai.general.net.MethodHandler.java

/**
 * The specified instance must be an instance of the class that defines the method or a
 * subclass of that class. It may be null for static methods.
 *
 * The method must be publicly accessible and it must be defined public in a class that is
 * public. If the method is defined in a nested class, both the nested class and the outer class
 * must be public.//from   www.  ja v a 2s .com
 *
 * Event methods must have exactly 1 parameter that accepts the publish or event data.
 * Any return values or exceptions thrown by an event method will be ignored.
 *
 * RPC call methods may have any number of parameters, return any value and throw exceptions.
 *
 * Method parameters must hava a POJO type. This includes primitive Java types or their arrays,
 * and bean types, i.e. classes that declare getters and setters for each field.
 *
 * @param name A unique name for the MethodHandler.
 * @param catchall True if this a catch-all handler.
 * @param instance Instance associated with method. May be null for static methods.
 * @param method The method to be called.
 * @throws IllegalArgumentException if the arguments are invalid or incompatible with each other.
 */
public MethodHandler(String name, boolean catchall, Object instance, Method method) {
    super(name, catchall);
    if (!Modifier.isStatic(method.getModifiers())) {
        if (instance == null) {
            throw new IllegalArgumentException("Non-static method requires instance.");
        }
        if (!method.getDeclaringClass().isInstance(instance)) {
            throw new IllegalArgumentException("Incompatible instance object.");
        }
    }
    this.instance_ = instance;
    this.method_ = method;
    parameter_types_ = method.getParameterTypes();
    json_parser_ = new ObjectMapper();
}

From source file:org.apache.camel.spring.util.MainRunner.java

public void runMethodWithoutCatchingExceptions()
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (delay > 0) {
        try {//from w w  w  . java  2s. c  o  m
            Thread.sleep(delay);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
    Method method = main.getMethod("main", String[].class);
    if (!Modifier.isStatic(method.getModifiers())) {
        throw new IllegalArgumentException("The main method is not static!: " + method);
    }
    Object[] arguments = { getArgs() };
    method.invoke(null, arguments);
}

From source file:org.eclipse.wb.internal.core.model.description.helpers.FactoryDescriptionHelper.java

/**
 * @return <code>true</code> if given {@link Method} modifiers are valid to consider this
 *         {@link Method} as possible factory methods. Usually we require "public" visibility.
 *         However for "local" factory methods we allow any visibility.
 *///from  w w  w .j  av  a 2 s .co m
private static boolean hasValidVisibility(AstEditor editor, Method factoryMethod) {
    // ignore visibility, if "local" factory method
    {
        String editorTypeName = editor.getModelUnit().findPrimaryType().getFullyQualifiedName();
        String factoryTypeName = factoryMethod.getDeclaringClass().getName();
        if (editorTypeName.equals(factoryTypeName)) {
            return true;
        }
    }
    // ensure "public" visibility
    int modifiers = factoryMethod.getModifiers();
    return java.lang.reflect.Modifier.isPublic(modifiers);
}

From source file:com.sinosoft.one.mvc.web.impl.module.ErrorHandlerDispatcher.java

public ErrorHandlerDispatcher(ControllerErrorHandler errorHandler) {
    this.errorHandler = errorHandler;
    Method[] methods = this.errorHandler.getClass().getMethods();
    for (final Method method : methods) {
        if (Modifier.isAbstract(method.getModifiers()) || Modifier.isStatic(method.getModifiers())) {
            continue;
        }/*w  w w  .  j  av  a 2s .c  om*/
        if (method.getName().equals("onError")) {
            final Class<?>[] parameterClasses = method.getParameterTypes();
            if (parameterClasses.length == 2 && parameterClasses[INVOCATION_INDEX] == Invocation.class
                    && Throwable.class.isAssignableFrom(parameterClasses[THROWABLE_INDEX])) {
                delegates.add(new ErrorHandlerDelegate() {

                    @Override
                    public Method getMethod() {
                        return method;
                    }

                    @Override
                    public Object onError(Invocation inv, Throwable ex) throws Throwable {
                        Object[] args = new Object[] { inv, ex };
                        try {
                            return method.invoke(ErrorHandlerDispatcher.this.errorHandler, args);
                        } catch (Throwable e) {
                            logger.error("error happened when handling error " + ex.getClass() + " at "
                                    + ErrorHandlerDispatcher.this.toString());
                            throw e;
                        }
                    }
                });
            }
        }
    }
    Collections.sort(delegates, new Comparator<ErrorHandlerDelegate>() {

        public int compare(ErrorHandlerDelegate o1, ErrorHandlerDelegate o2) {
            if (o1.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o2.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return 1;
            } else if (o2.getMethod().getParameterTypes()[THROWABLE_INDEX]
                    .isAssignableFrom(o1.getMethod().getParameterTypes()[THROWABLE_INDEX])) {
                return -1;
            } else {
                return o1.getMethod().getParameterTypes()[THROWABLE_INDEX].getName()
                        .compareTo(o2.getMethod().getParameterTypes()[THROWABLE_INDEX].getName());
            }
        }
    });
}