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:edu.cmu.tetrad.util.TetradSerializableUtils.java

/**
 * @return a reference to the public static serializableInstance() method of
 * clazz, if there is one; otherwise, returns null.
 *///from www .j  a  v  a  2s.  c o m
private Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
        if ("serializableInstance".equals(method.getName())) {
            Class[] parameterTypes = method.getParameterTypes();

            if (!(parameterTypes.length == 0)) {
                continue;
            }

            if (!(Modifier.isStatic(method.getModifiers()))) {
                continue;
            }

            if (Modifier.isAbstract(method.getModifiers())) {
                continue;
            }

            return method;
        }
    }

    return null;
}

From source file:edu.cmu.tetradapp.util.TetradSerializableUtils.java

/**
 * Returns a reference to the public static serializableInstance() method of
 * clazz, if there is one; otherwise, returns null.
 *///from   w  w w.  j a  v a 2  s  . c  o m
public Method serializableInstanceMethod(Class clazz) {
    Method[] methods = clazz.getMethods();

    for (Method method : methods) {
        if ("serializableInstance".equals(method.getName())) {
            Class[] parameterTypes = method.getParameterTypes();

            if (!(parameterTypes.length == 0)) {
                continue;
            }

            if (!(Modifier.isStatic(method.getModifiers()))) {
                continue;
            }

            if (Modifier.isAbstract(method.getModifiers())) {
                continue;
            }

            return method;
        }
    }

    return null;
}

From source file:org.apache.axis2.jaxws.server.endpoint.injection.impl.WebServiceContextInjectorImpl.java

public void injectOnMethod(Object resource, Object instance, Method method) throws ResourceInjectionException {
    if (instance == null) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot inject Resource on a null Service Instance.");
        }//  www  .  j  a  v a2 s  . c  om
        throw new ResourceInjectionException(Messages.getMessage("WebServiceContextInjectionImplErr1"));
    }
    if (method == null) {
        if (log.isDebugEnabled()) {
            log.debug("Cannot inject WebServiceContext on ServiceInstance Method, method cannot be NULL");
        }
        throw new ResourceInjectionException(Messages.getMessage("WebServiceContextInjectionImplErr3"));
    }
    try {
        if (!Modifier.isPublic(method.getModifiers())) {
            setAccessible(method, true);
        }
        method.invoke(instance, resource);
        return;
    } catch (IllegalAccessException e) {
        throw new ResourceInjectionException(e);
    } catch (InvocationTargetException e) {
        throw new ResourceInjectionException(e);
    }

}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Find get methods with no params. All getters that aren't Native, Static,
 * Abstract, Synthetic, or Bridge are returned.
 * //  w w  w  .j  a  va 2s .c  om
 * @param clazz
 *          the clazz
 * @return the list
 */
public synchronized static List<Method> findGetMethodsWithNoParams(Class<?> clazz) {

    /* if a cache already exists simply return it */
    List<Method> returnMethods = cachedMethods.get(clazz);

    if (returnMethods == null) {
        /* create a new cache and return it */
        returnMethods = new ArrayList<Method>();

        for (Method method : findAllMethods(clazz)) {

            // check for compiler introduced methods, as well as native methods.
            // simply ignore these methods, as they are probably not what we are
            // looking for.

            int modifiers = method.getModifiers();

            if (Modifier.isNative(modifiers) //
                    || Modifier.isStatic(modifiers) //
                    || Modifier.isAbstract(modifiers) //
                    || method.isSynthetic() //
                    || method.isBridge()) {
                continue;
            }

            // if its a getter then add it to the list
            if (isIs(method) || isGetter(method)) {
                if (!doesMethodHaveParams(method)) {
                    returnMethods.add(method);
                }
            }
        }

        cachedMethods.put(clazz, returnMethods);
    }

    return returnMethods;
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Returns true if indicated type matches the JAX-RPC enumeration class.
 * Note: supports JSR 101 version 0.6 Public Draft
 *
 * @param cls//w ww  .ja va2 s  .  com
 * @return
 */
public static boolean isEnumClass(Class cls) {

    try {
        java.lang.reflect.Method m = cls.getMethod("getValue", null);
        java.lang.reflect.Method m2 = cls.getMethod("toString", null);

        if ((m != null) && (m2 != null)) {
            java.lang.reflect.Method m3 = cls.getDeclaredMethod("fromString",
                    new Class[] { java.lang.String.class });
            java.lang.reflect.Method m4 = cls.getDeclaredMethod("fromValue", new Class[] { m.getReturnType() });

            if ((m3 != null) && Modifier.isStatic(m3.getModifiers()) && Modifier.isPublic(m3.getModifiers())
                    && (m4 != null) && Modifier.isStatic(m4.getModifiers())
                    && Modifier.isPublic(m4.getModifiers())) {

                // Return false if there is a setValue member method
                try {
                    if (cls.getMethod("setValue", new Class[] { m.getReturnType() }) == null) {
                        return true;
                    }

                    return false;
                } catch (java.lang.NoSuchMethodException e) {
                    return true;
                }
            }
        }
    } catch (java.lang.NoSuchMethodException e) {
    }

    return false;
}

From source file:com.github.jinahya.sql.database.metadata.bind.MetadataContext.java

private Set<String> getMethodNames() {

    if (methodNames == null) {
        methodNames = new HashSet<String>();
        for (final Method method : DatabaseMetaData.class.getMethods()) {
            if (method.getDeclaringClass() != DatabaseMetaData.class) {
                continue;
            }/*from w  w w .ja va2s. c om*/
            final int modifier = method.getModifiers();
            if (Modifier.isStatic(modifier)) {
                continue;
            }
            if (!Modifier.isPublic(modifier)) {
                continue;
            }
            methodNames.add(method.getName());
        }
    }

    return methodNames;
}

From source file:org.gradle.api.internal.AbstractClassGenerator.java

private <T> Class<? extends T> generateUnderLock(Class<T> type) {
    Map<Class<?>, Class<?>> cache = GENERATED_CLASSES.get(getClass());
    if (cache == null) {
        // WeakHashMap won't work here. It keeps a strong reference to the mapping value, which is the generated class in this case
        // However, the generated class has a strong reference to the source class (by extending it), so the keys will always be
        // strongly reachable while this Class is strongly reachable. Use weak references for both key and value of the mapping instead.
        cache = new ReferenceMap(AbstractReferenceMap.WEAK, AbstractReferenceMap.WEAK);
        GENERATED_CLASSES.put(getClass(), cache);
    }//from   ww w.j  av a 2  s  .  c om
    Class<?> generatedClass = cache.get(type);
    if (generatedClass != null) {
        return generatedClass.asSubclass(type);
    }

    if (Modifier.isPrivate(type.getModifiers())) {
        throw new GradleException(
                String.format("Cannot create a proxy class for private class '%s'.", type.getSimpleName()));
    }
    if (Modifier.isAbstract(type.getModifiers())) {
        throw new GradleException(
                String.format("Cannot create a proxy class for abstract class '%s'.", type.getSimpleName()));
    }

    Class<? extends T> subclass;
    try {
        ClassMetaData classMetaData = inspectType(type);

        ClassBuilder<T> builder = start(type, classMetaData);

        builder.startClass();

        if (!DynamicObjectAware.class.isAssignableFrom(type)) {
            if (ExtensionAware.class.isAssignableFrom(type)) {
                throw new UnsupportedOperationException(
                        "A type that implements ExtensionAware must currently also implement DynamicObjectAware.");
            }
            builder.mixInDynamicAware();
        }
        if (!GroovyObject.class.isAssignableFrom(type)) {
            builder.mixInGroovyObject();
        }
        builder.addDynamicMethods();
        if (classMetaData.conventionAware && !IConventionAware.class.isAssignableFrom(type)) {
            builder.mixInConventionAware();
        }

        Class noMappingClass = Object.class;
        for (Class<?> c = type; c != null && noMappingClass == Object.class; c = c.getSuperclass()) {
            if (c.getAnnotation(NoConventionMapping.class) != null) {
                noMappingClass = c;
            }
        }

        Set<PropertyMetaData> conventionProperties = new HashSet<PropertyMetaData>();

        for (PropertyMetaData property : classMetaData.properties.values()) {
            if (SKIP_PROPERTIES.contains(property.name)) {
                continue;
            }

            if (property.injector) {
                builder.addInjectorProperty(property);
                for (Method getter : property.getters) {
                    builder.applyServiceInjectionToGetter(property, getter);
                }
                for (Method setter : property.setters) {
                    builder.applyServiceInjectionToSetter(property, setter);
                }
                continue;
            }

            boolean needsConventionMapping = false;
            if (classMetaData.isExtensible()) {
                for (Method getter : property.getters) {
                    if (!Modifier.isFinal(getter.getModifiers())
                            && !getter.getDeclaringClass().isAssignableFrom(noMappingClass)) {
                        needsConventionMapping = true;
                        break;
                    }
                }
            }

            if (needsConventionMapping) {
                conventionProperties.add(property);
                builder.addConventionProperty(property);
                for (Method getter : property.getters) {
                    builder.applyConventionMappingToGetter(property, getter);
                }
            }

            if (needsConventionMapping) {
                for (Method setter : property.setters) {
                    if (!Modifier.isFinal(setter.getModifiers())) {
                        builder.applyConventionMappingToSetter(property, setter);
                    }
                }
            }
        }

        Set<Method> actionMethods = classMetaData.missingOverloads;
        for (Method method : actionMethods) {
            builder.addActionMethod(method);
        }

        // Adds a set method for each mutable property
        for (PropertyMetaData property : classMetaData.properties.values()) {
            if (property.setters.isEmpty()) {
                continue;
            }
            if (Iterable.class.isAssignableFrom(property.getType())) {
                // Currently not supported
                continue;
            }

            if (property.setMethods.isEmpty()) {
                for (Method setter : property.setters) {
                    builder.addSetMethod(property, setter);
                }
            } else if (conventionProperties.contains(property)) {
                for (Method setMethod : property.setMethods) {
                    builder.applyConventionMappingToSetMethod(property, setMethod);
                }
            }
        }

        for (Constructor<?> constructor : type.getConstructors()) {
            if (Modifier.isPublic(constructor.getModifiers())) {
                builder.addConstructor(constructor);
            }
        }

        subclass = builder.generate();
    } catch (Throwable e) {
        throw new GradleException(
                String.format("Could not generate a proxy class for class %s.", type.getName()), e);
    }

    cache.put(type, subclass);
    cache.put(subclass, subclass);
    return subclass;
}

From source file:org.apache.camel.component.bean.BeanInfo.java

/**
 * Validates whether the given method is a valid candidate for Camel Bean Binding.
 *
 * @param clazz   the class//ww w  .j  a  v a 2  s  .  com
 * @param method  the method
 * @return true if valid, false to skip the method
 */
protected boolean isValidMethod(Class<?> clazz, Method method) {
    // must not be in the excluded list
    for (Method excluded : EXCLUDED_METHODS) {
        if (ObjectHelper.isOverridingMethod(excluded, method)) {
            // the method is overriding an excluded method so its not valid
            return false;
        }
    }

    // must be a public method
    if (!Modifier.isPublic(method.getModifiers())) {
        return false;
    }

    // return type must not be an Exchange and it should not be a bridge method
    if ((method.getReturnType() != null && Exchange.class.isAssignableFrom(method.getReturnType()))
            || method.isBridge()) {
        return false;
    }

    return true;
}

From source file:com.baidu.jprotobuf.mojo.PreCompileMojo.java

/**
 * Execute goal.//ww w .  j  a va 2s  .c o  m
 * 
 * @throws MojoExecutionException execution of the main class or one of the threads it generated failed.
 * @throws MojoFailureException something bad happened...
 */
public void execute() throws MojoExecutionException, MojoFailureException {
    if (isSkip()) {
        getLog().info("skipping execute as per configuraion");
        return;
    }
    if (killAfter != -1) {
        getLog().warn("Warning: killAfter is now deprecated. Do you need it ? Please comment on MEXEC-6.");
    }

    arguments = new String[] { outputParentDirectory.getAbsolutePath(), outputDirectory.getAbsolutePath(),
            filterClassPackage };

    if (getLog().isDebugEnabled()) {
        StringBuffer msg = new StringBuffer("Invoking : ");
        msg.append(mainClass);
        msg.append(".main(");
        for (int i = 0; i < arguments.length; i++) {
            if (i > 0) {
                msg.append(", ");
            }
            msg.append(arguments[i]);
        }
        msg.append(")");
        getLog().debug(msg);
    }

    final Log log = getLog();
    IsolatedThreadGroup threadGroup = new IsolatedThreadGroup(mainClass /* name */);
    Thread bootstrapThread = new Thread(threadGroup, new Runnable() {
        public void run() {
            long current = System.currentTimeMillis();
            try {

                Method main = Thread.currentThread().getContextClassLoader().loadClass(mainClass)
                        .getMethod("main", new Class[] { String[].class });
                if (!main.isAccessible()) {
                    getLog().debug("Setting accessibility to true in order to invoke main().");
                    main.setAccessible(true);
                }
                if (!Modifier.isStatic(main.getModifiers())) {
                    throw new MojoExecutionException(
                            "Can't call main(String[])-method because it is not static.");
                }
                main.invoke(null, new Object[] { arguments });
            } catch (NoSuchMethodException e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), new Exception(
                        "The specified mainClass doesn't contain a main method with appropriate signature.",
                        e));
            } catch (Exception e) { // just pass it on
                Thread.currentThread().getThreadGroup().uncaughtException(Thread.currentThread(), e);
            } finally {
                log.info("JProtobuf pre compile done time took: " + (System.currentTimeMillis() - current)
                        + "ms");
            }
        }
    }, mainClass + ".main()");
    bootstrapThread.setContextClassLoader(getClassLoader());
    setSystemProperties();

    bootstrapThread.start();
    joinNonDaemonThreads(threadGroup);
    // It's plausible that spontaneously a non-daemon thread might be created as we try and shut down,
    // but it's too late since the termination condition (only daemon threads) has been triggered.
    if (keepAlive) {
        getLog().warn(
                "Warning: keepAlive is now deprecated and obsolete. Do you need it? Please comment on MEXEC-6.");
        waitFor(0);
    }

    if (cleanupDaemonThreads) {

        terminateThreads(threadGroup);

        try {
            threadGroup.destroy();
        } catch (IllegalThreadStateException e) {
            getLog().warn("Couldn't destroy threadgroup " + threadGroup, e);
        }
    }

    if (originalSystemProperties != null) {
        System.setProperties(originalSystemProperties);
    }

    synchronized (threadGroup) {
        if (threadGroup.uncaughtException != null) {
            throw new MojoExecutionException("An exception occured while executing the Java class. "
                    + threadGroup.uncaughtException.getMessage(), threadGroup.uncaughtException);
        }
    }

    registerSourceRoots();
}

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

private void writePropertyMethods(ClassVisitor visitor, Type generatedType, ModelStructSchema<?> managedSchema,
        ModelStructSchema<?> delegateSchema) {
    Collection<String> delegatePropertyNames;
    if (delegateSchema != null) {
        ImmutableSet.Builder<String> builder = ImmutableSet.builder();
        for (ModelProperty<?> delegateProperty : delegateSchema.getProperties()) {
            builder.add(delegateProperty.getName());
        }//w  w w .  j a v  a2 s  . c  om
        delegatePropertyNames = builder.build();
    } else {
        delegatePropertyNames = Collections.emptySet();
    }
    Class<?> managedTypeClass = managedSchema.getType().getConcreteClass();
    for (ModelProperty<?> property : managedSchema.getProperties()) {
        String propertyName = property.getName();
        // Delegated properties are handled in writeDelegateMethods()
        if (delegatePropertyNames.contains(propertyName)) {
            continue;
        }
        switch (property.getStateManagementType()) {
        case MANAGED:
            writeGetters(visitor, generatedType, property);
            writeSetter(visitor, generatedType, property);
            break;

        case UNMANAGED:
            String getterName = getGetterName(propertyName);
            Method getterMethod;
            try {
                getterMethod = managedTypeClass.getMethod(getterName);
            } catch (NoSuchMethodException e) {
                throw new IllegalStateException(String.format("Cannot find getter '%s' on type %s", getterName,
                        managedTypeClass.getName()), e);
            }
            if (!Modifier.isFinal(getterMethod.getModifiers()) && !propertyName.equals("metaClass")) {
                writeNonAbstractMethodWrapper(visitor, generatedType, managedTypeClass, getterMethod);
            }
            break;
        }
    }
}