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.sworddance.beans.ProxyMapperImpl.java

/**
 * @param method/*from  www.ja  v  a 2  s  .c  o m*/
 * @param args
 * @param actualObject
 * @return
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
private Object doInvoke(Method method, Object[] args) throws IllegalAccessException, InvocationTargetException {
    O actualObject;
    if ((method.getModifiers() & Modifier.STATIC) != Modifier.STATIC) {
        // not a static method
        actualObject = getRealObject(true, "need object to call a non-static method ", this, " method=", method,
                "(", join(args), ")");
    } else {
        actualObject = null;
    }
    try {
        return method.invoke(actualObject, args);
    } catch (RuntimeException e) {
        // would like to log or annotate somehow ..
        // changing type of exception is bad so we will throw as an exception that will normally be unwrapped.
        throw new InvocationTargetException(e, this + " method=" + method + "(" + join(args) + ")");
    }
}

From source file:javadz.beanutils.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 ava  2s . 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 
 * @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 {
        // Check the cache first
        Method method = getCachedMethod(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()));
        }

        setMethodAccessible(method); // Default access superclass workaround

        cacheMethod(md, method);
        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) {
        cacheMethod(md, bestMatch);
    } else {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:net.camelpe.extension.camel.typeconverter.CdiTypeConverterBuilder.java

private TypeConverterHolder buildFallbackTypeConverterFromFallbackConverterAnnotatedClass(final Class<?> type,
        final Method method) throws IllegalArgumentException {
    ensureFallbackConverterMethodIsValid(type, method);
    this.log.trace("Building Fallback TypeConverter from method [{}] ...", method);
    final TypeConverter typeConverter;
    final boolean canPromote = method.isAnnotationPresent(FallbackConverter.class)
            ? method.getAnnotation(FallbackConverter.class).canPromote()
            : false;/*  ww  w. j  a va 2s.  com*/
    if (isStatic(method.getModifiers())) {
        typeConverter = new StaticMethodFallbackTypeConverter(method, this.typeConverterRegistry);
    } else {
        typeConverter = new CdiInstanceMethodFallbackTypeConverter(new CdiInjector(this.beanManager), method,
                this.typeConverterRegistry);
    }
    this.log.trace("Built Fallback TypeConverter [{}]", typeConverter, method);

    return TypeConverterHolder.newFallbackTypeConverterHolder(typeConverter, canPromote);
}

From source file:org.itest.impl.ITestRandomObjectGeneratorImpl.java

protected Object newDynamicProxy(Type type, final Map<String, Type> itestGenericMap,
        final ITestContext iTestContext) {
    final Class<?> clazz = ITestTypeUtil.getRawClass(type);
    final Map<String, Object> methodResults = new HashMap<String, Object>();

    Object res = Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {

                @Override/*from   w  ww. j  av  a  2s.  c  o  m*/
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    String mSignature = ITestUtils.getMethodSingnature(method, true);
                    if (methodResults.containsKey(mSignature)) {
                        return methodResults.get(mSignature);
                    }
                    throw new ITestMethodExecutionException(
                            "Implementation of " + clazz.getName() + "." + mSignature + " not provided", null);
                }
            });

    Map<String, Type> map = ITestTypeUtil.getTypeMap(type, new HashMap<String, Type>());

    Class<?> t = clazz;
    do {
        for (Method m : t.getDeclaredMethods()) {
            if (!Modifier.isStatic(m.getModifiers())) {
                String signature = ITestUtils.getMethodSingnature(m, true);
                ITestParamState iTestState = iTestContext.getCurrentParam();
                ITestParamState mITestState = iTestState == null ? null : iTestState.getElement(signature);
                if (null == mITestState) {
                    mITestState = iTestState == null ? null
                            : iTestState.getElement(signature = ITestUtils.getMethodSingnature(m, false));
                }
                fillMethod(m, res, signature, map, iTestContext, methodResults);
            }
        }
        map = ITestTypeUtil.getTypeMap(clazz, map);
    } while ((t = t.getSuperclass()) != null);

    return res;
}

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

public <R> ModelSchemaExtractionResult<R> extract(final ModelSchemaExtractionContext<R> extractionContext,
        ModelSchemaStore store, final ModelSchemaCache cache) {
    ModelType<R> type = extractionContext.getType();
    Class<? super R> clazz = type.getRawClass();
    if (isTarget(type)) {
        validateType(type, extractionContext);

        Iterable<Method> methods = Arrays.asList(clazz.getMethods());
        if (!clazz.isInterface()) {
            methods = filterIgnoredMethods(methods);
        }// ww w  .  ja va 2 s  . co m
        ImmutableListMultimap<String, Method> methodsByName = Multimaps.index(methods,
                new Function<Method, String>() {
                    public String apply(Method method) {
                        return method.getName();
                    }
                });

        ensureNoOverloadedMethods(extractionContext, methodsByName);

        List<ModelProperty<?>> properties = Lists.newLinkedList();
        List<Method> handled = Lists.newArrayListWithCapacity(clazz.getMethods().length);
        ReturnTypeSpecializationOrdering returnTypeSpecializationOrdering = new ReturnTypeSpecializationOrdering();

        for (String methodName : methodsByName.keySet()) {
            if (methodName.startsWith("get") && !methodName.equals("get")) {
                ImmutableList<Method> getterMethods = methodsByName.get(methodName);

                // The overload check earlier verified that all methods for are equivalent for our purposes
                // So, taking the first one with the most specialized return type is fine.
                Method sampleMethod = returnTypeSpecializationOrdering.max(getterMethods);

                boolean abstractGetter = Modifier.isAbstract(sampleMethod.getModifiers());

                if (sampleMethod.getParameterTypes().length != 0) {
                    throw invalidMethod(extractionContext, "getter methods cannot take parameters",
                            sampleMethod);
                }

                Character getterPropertyNameFirstChar = methodName.charAt(3);
                if (!Character.isUpperCase(getterPropertyNameFirstChar)) {
                    throw invalidMethod(extractionContext,
                            "the 4th character of the getter method name must be an uppercase character",
                            sampleMethod);
                }

                ModelType<?> returnType = ModelType.returnType(sampleMethod);

                String propertyNameCapitalized = methodName.substring(3);
                String propertyName = StringUtils.uncapitalize(propertyNameCapitalized);
                String setterName = "set" + propertyNameCapitalized;
                ImmutableList<Method> setterMethods = methodsByName.get(setterName);

                boolean isWritable = !setterMethods.isEmpty();
                if (isWritable) {
                    Method setter = setterMethods.get(0);

                    if (!abstractGetter) {
                        throw invalidMethod(extractionContext,
                                "setters are not allowed for non-abstract getters", setter);
                    }
                    validateSetter(extractionContext, returnType, setter);
                    handled.addAll(setterMethods);
                }

                if (abstractGetter) {
                    ImmutableSet<ModelType<?>> declaringClasses = ImmutableSet
                            .copyOf(Iterables.transform(getterMethods, new Function<Method, ModelType<?>>() {
                                public ModelType<?> apply(Method input) {
                                    return ModelType.of(input.getDeclaringClass());
                                }
                            }));

                    boolean unmanaged = Iterables.any(getterMethods, new Predicate<Method>() {
                        public boolean apply(Method input) {
                            return input.getAnnotation(Unmanaged.class) != null;
                        }
                    });

                    properties.add(ModelProperty.of(returnType, propertyName, isWritable, declaringClasses,
                            unmanaged));
                }
                handled.addAll(getterMethods);
            }
        }

        Iterable<Method> notHandled = Iterables.filter(methodsByName.values(),
                Predicates.not(Predicates.in(handled)));

        // TODO - should call out valid getters without setters
        if (!Iterables.isEmpty(notHandled)) {
            throw invalidMethods(extractionContext, "only paired getter/setter methods are supported",
                    notHandled);
        }

        Class<R> concreteClass = type.getConcreteClass();
        final ModelSchema<R> schema = createSchema(extractionContext, store, type, properties, concreteClass);
        Iterable<ModelSchemaExtractionContext<?>> propertyDependencies = Iterables.transform(properties,
                new Function<ModelProperty<?>, ModelSchemaExtractionContext<?>>() {
                    public ModelSchemaExtractionContext<?> apply(final ModelProperty<?> property) {
                        return toPropertyExtractionContext(extractionContext, property, cache);
                    }
                });

        return new ModelSchemaExtractionResult<R>(schema, propertyDependencies);
    } else {
        return null;
    }
}

From source file:com.opengamma.language.external.ExternalFunctionHandler.java

/**
 * Creates a handler wrapper for a given class.
 * /*from w ww  .j  av  a 2s  .c  o m*/
 * @param clazz the class containing external function methods
 */
public ExternalFunctionHandler(final Class<?> clazz) {
    final Constructor<?>[] constructors = clazz.getConstructors();
    final Method[] methods = clazz.getMethods();
    final ArrayList<PublishedFunction> functions = new ArrayList<PublishedFunction>(
            constructors.length + methods.length);
    // Only need an instance of the class if one or more annotated methods are not static. In this case, the same
    // instance will be re-used for each non-static method. If instantiation fails (e.g. no default constructor), just
    // skip instance methods and log warnings.
    Object sharedInstance = null;
    boolean instantiateFailed = false;
    for (Constructor<?> constructor : constructors) {
        if (!constructor.isAnnotationPresent(ExternalFunction.class)) {
            continue;
        }
        s_logger.debug("Found constructor {}", constructor);
        // If there is a constructor method, can only have static declarations
        instantiateFailed = true;
        functions.add(new ConstructorWrapper(constructor));
    }
    for (Method method : methods) {
        if (!method.isAnnotationPresent(ExternalFunction.class)) {
            continue;
        }
        s_logger.debug("Found method {}", method);
        final Object instance;
        if (Modifier.isStatic(method.getModifiers())) {
            instance = null;
        } else {
            if (instantiateFailed) {
                s_logger.warn("Skipping method {}", method);
                continue;
            } else if (sharedInstance == null) {
                sharedInstance = tryGetInstance(clazz);
                if (sharedInstance == null) {
                    s_logger.warn("Default instantiation failed for {}", clazz);
                    s_logger.warn("Skipping method {}", method);
                    instantiateFailed = true;
                    continue;
                }
            }
            instance = sharedInstance;
        }
        functions.add(new MethodWrapper(method, instance));
    }
    functions.trimToSize();
    _functions = functions;
}

From source file:org.exoplatform.social.core.test.AbstractCoreTest.java

@Override
/**/*  www .ja  va2 s.  c om*/
 * Override to run the test and assert its state.
 * @throws Throwable if any exception is thrown
 */
protected void runTest() throws Throwable {
    String fName = getName();
    assertNotNull("TestCase.fName cannot be null", fName); // Some VMs crash when calling getMethod(null,null);
    Method runMethod = null;
    try {
        // use getMethod to get all public inherited
        // methods. getDeclaredMethods returns all
        // methods of this class but excludes the
        // inherited ones.
        runMethod = getClass().getMethod(fName, (Class[]) null);
    } catch (NoSuchMethodException e) {
        fail("Method \"" + fName + "\" not found");
    }
    if (!Modifier.isPublic(runMethod.getModifiers())) {
        fail("Method \"" + fName + "\" should be public");
    }

    try {
        MaxQueryNumber queryNumber = runMethod.getAnnotation(MaxQueryNumber.class);
        if (queryNumber != null) {
            wantCount = true;
            maxQuery = queryNumber.value();
        }
        runMethod.invoke(this);
    } catch (InvocationTargetException e) {
        e.fillInStackTrace();
        throw e.getTargetException();
    } catch (IllegalAccessException e) {
        e.fillInStackTrace();
        throw e;
    }

    if (wantCount && count > maxQuery) {
        throw new AssertionFailedError(
                "" + count + " JDBC queries was executed but the maximum is : " + maxQuery);
    }

}

From source file:org.apache.niolex.commons.reflect.MethodFilter.java

/**
 * This is the override of super method.
 * @see org.apache.niolex.commons.reflect.MethodUtil.Filter#isValid(java.lang.reflect.Method)
 */// w w  w.  j a  va  2  s. com
@Override
public boolean isValid(Method m) {
    if (methodName != null && !methodName.equals(m.getName())) {
        return false;
    }
    if (returnType != null && !ClassUtils.isAssignable(m.getReturnType(), returnType, true)) {
        return false;
    }
    if (parameterTypes != null && !ClassUtils.isAssignable(parameterTypes, m.getParameterTypes(), true)) {
        return false;
    }
    if (!includeStatic && Modifier.isStatic(m.getModifiers())) {
        return false;
    }
    if (!includeAbstract && Modifier.isAbstract(m.getModifiers())) {
        return false;
    }
    if (!includeSynthetic && m.isSynthetic()) {
        return false;
    }
    return true;
}

From source file:org.apache.lens.cli.TestLensQueryCommands.java

@Test
public void testProxyLensQuery() throws Exception {
    LensClient client = new LensClient();
    QueryHandle handle = client.executeQueryAsynch("cube select id,name from test_dim", "proxyTestQuery",
            new LensConf());
    client.getStatement().waitForQueryToComplete(handle);
    LensQuery query = client.getQueryDetails(handle);
    ProxyLensQuery proxyQuery = new ProxyLensQuery(client.getStatement(), handle);
    Assert.assertEquals(query.getStatus().successful(), proxyQuery.getStatus().successful());
    Assert.assertEquals(query.getSubmissionTime(), proxyQuery.getSubmissionTime());
    Assert.assertEquals(query.getFinishTime(), proxyQuery.getFinishTime());

    //Check is any new getters are added to LensQuery. If yes, ProxyLensQuery should be updated too
    Set<String> lensQueryMethods = new HashSet<String>();
    for (Method m : query.getClass().getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers()) && !m.getName().startsWith("hash")
                && !m.getName().startsWith("equals")) {
            lensQueryMethods.add(m.getName());
        }/*from ww w.  j a  v  a2 s . c om*/
    }

    Set<String> proxyLensQueryMethods = new HashSet<String>();
    for (Method m : proxyQuery.getClass().getDeclaredMethods()) {
        if (Modifier.isPublic(m.getModifiers())) {
            proxyLensQueryMethods.add(m.getName());
        }
    }

    log.info("Methods in LensQuery: " + lensQueryMethods + "\nMethods in ProxyLensQuery: "
            + proxyLensQueryMethods);
    assertTrue(lensQueryMethods.containsAll(proxyLensQueryMethods),
            "Methods in LensQuery and ProxyLensQuery do not match");

    //Check equals and hashCode override
    ProxyLensQuery proxyQuery2 = new ProxyLensQuery(client.getStatement(), handle);
    Assert.assertEquals(proxyQuery, proxyQuery2);
    Assert.assertEquals(proxyQuery, query);
    Assert.assertEquals(proxyQuery.hashCode(), proxyQuery2.hashCode());
    Assert.assertEquals(proxyQuery.hashCode(), query.hashCode());

    client.closeConnection();
}

From source file:com.alta189.beaker.CommonEventManager.java

/**
 * Registers all the {@link EventHandler}s contained in the
 * Listener/* w  ww  .j ava  2s. c  o m*/
 *
 * @param listener registration, not null
 * @param owner owner of the listener, not null
 * @throws com.alta189.beaker.exceptions.EventRegistrationException
 */
@Override
public void registerListener(Listener listener, Named owner) throws EventRegistrationException {
    try {
        Validate.notNull(listener, "Listener cannot be null");
        Validate.notNull(owner, "Owner cannot be null");
        Validate.notNull(owner.getName(), "Owner's name cannot be null");
        Validate.notEmpty(owner.getName(), "Owner's name cannot be empty");

        for (Method method : listener.getClass().getDeclaredMethods()) {
            if (!method.isAnnotationPresent(EventHandler.class)) {
                continue;
            }

            EventHandler handler = method.getAnnotation(EventHandler.class);
            Validate.notNull(handler.ignoreCancelled(), "ignoredCancelled cannot be null");
            Validate.notNull(handler.priority(), "Priority cannot be null");

            if (!Modifier.isPublic(method.getModifiers())) {
                throw new EventRegistrationException("Method has to be public");
            }

            if (Modifier.isStatic(method.getModifiers())) {
                throw new EventRegistrationException("Method cannot be static");
            }

            if (method.getParameterTypes().length != 1) {
                throw new EventRegistrationException("Method cannot have more than one parameter");
            }

            if (!Event.class.isAssignableFrom(method.getParameterTypes()[0])) {
                throw new EventRegistrationException("Method's parameter type has to extend class");
            }

            EventExecutor executor = new AnnotatedEventExecutor(listener, method);
            HandlerRegistration registration = new HandlerRegistration(executor, handler.priority(),
                    handler.ignoreCancelled(), owner);

            List<HandlerRegistration> list = getRegistrationList(
                    (Class<? extends Event>) method.getParameterTypes()[0], true);
            list.add(registration);
            sortList(list);
        }
    } catch (EventRegistrationException e) {
        throw e;
    } catch (Exception e) {
        throw new EventRegistrationException(e);
    }
}