Example usage for java.lang.reflect Modifier isPublic

List of usage examples for java.lang.reflect Modifier isPublic

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPublic.

Prototype

public static boolean isPublic(int mod) 

Source Link

Document

Return true if the integer argument includes the public modifier, false otherwise.

Usage

From source file:com.google.gwtjsonrpc.server.JsonServlet.java

private static Map<String, MethodHandle> methods(final RemoteJsonService impl) {
    final Class<? extends RemoteJsonService> d = findInterface(impl.getClass());
    if (d == null) {
        return Collections.<String, MethodHandle>emptyMap();
    }//ww w. j a v  a 2  s.com

    final Map<String, MethodHandle> r = new HashMap<String, MethodHandle>();
    for (final Method m : d.getMethods()) {
        if (!Modifier.isPublic(m.getModifiers())) {
            continue;
        }

        if (m.getReturnType() != Void.TYPE) {
            continue;
        }

        final Class<?>[] params = m.getParameterTypes();
        if (params.length < 1) {
            continue;
        }

        if (!params[params.length - 1].isAssignableFrom(AsyncCallback.class)) {
            continue;
        }

        final MethodHandle h = new MethodHandle(impl, m);
        r.put(h.getName(), h);
    }
    return Collections.unmodifiableMap(r);
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

public static boolean isPublic(Method method) {
    return Modifier.isPublic(method.getModifiers());
}

From source file:com.tmind.framework.pub.utils.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  ww  .j av a2s . 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
 */
public static Method getMatchingAccessibleMethod(Class clazz, String methodName, Class[] parameterTypes) {
    // trace logging
    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 = (Method) cache.get(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()));
        }

        try {
            //
            // XXX Default access superclass workaround
            //
            // When a public class has a default access superclass
            // with public methods, these methods are accessible.
            // Calling them from compiled code works fine.
            //
            // Unfortunately, using reflection to invoke these methods
            // seems to (wrongly) to prevent access even when the method
            // modifer is public.
            //
            // The following workaround solves the problem but will only
            // work from sufficiently privilages code.
            //
            // Better workarounds would be greatfully accepted.
            //
            method.setAccessible(true);

        } catch (SecurityException se) {
            // log but continue just in case the method.invoke works anyway
            if (!loggedAccessibleWarning) {
                boolean vunerableJVM = false;
                try {
                    String specVersion = System.getProperty("java.specification.version");
                    if (specVersion.charAt(0) == '1'
                            && (specVersion.charAt(0) == '0' || specVersion.charAt(0) == '1'
                                    || specVersion.charAt(0) == '2' || specVersion.charAt(0) == '3')) {

                        vunerableJVM = true;
                    }
                } catch (SecurityException e) {
                    // don't know - so display warning
                    vunerableJVM = true;
                }
                if (vunerableJVM) {
                    log.warn("Current Security Manager restricts use of workarounds for reflection bugs "
                            + " in pre-1.4 JVMs.");
                }
                loggedAccessibleWarning = true;
            }
            log.debug("Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.", se);
        }
        cache.put(md, method);
        return method;

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

    // search through all methods
    int paramSize = parameterTypes.length;
    Method[] methods = clazz.getMethods();
    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(methods[i]);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + methods[i]);
                        }
                        try {
                            //
                            // XXX Default access superclass workaround
                            // (See above for more details.)
                            //
                            method.setAccessible(true);

                        } catch (SecurityException se) {
                            // log but continue just in case the method.invoke works anyway
                            if (!loggedAccessibleWarning) {
                                log.warn(
                                        "Cannot use JVM pre-1.4 access bug workaround due to restrictive security manager.");
                                loggedAccessibleWarning = true;
                            }
                            log.debug(
                                    "Cannot setAccessible on method. Therefore cannot use jvm access bug workaround.",
                                    se);
                        }
                        cache.put(md, method);
                        return method;
                    }

                    log.trace("Couldn't find accessible method.");
                }
            }
        }
    }

    // didn't find a match
    log.trace("No match found.");
    return null;
}

From source file:org.apache.axis.description.JavaServiceDesc.java

/**
 * Synchronize an existing OperationDesc to a java.lang.Method.
 *
 * This method is used when the deployer has specified operation metadata
 * and we want to match that up with a real java Method so that the
 * Operation-level dispatch carries us all the way to the implementation.
 * Search the declared methods on the implementation class to find one
 * with an argument list which matches our parameter list.
 *//*from  ww  w  . j  a v a2 s .  c om*/
private void syncOperationToClass(OperationDesc oper, Class implClass) {
    // ------------------------------------------------
    // Developer Note:
    //
    // The goal of the sync code is to associate
    // the OperationDesc/ParamterDesc with the
    // target Method.  There are a number of ways to get to this
    // point depending on what information
    // is available.  Here are the main scenarios:
    //
    // A) Deployment with wsdd (non-skeleton):
    //   * OperationDesc/ParameterDesc loaded from deploy.wsdd
    //   * Loaded ParameterDesc does not have javaType,
    //     so it is discovered using the TypeMappingRegistry
    //     (also loaded via deploy.wsdd) and the
    //     typeQName specified by the ParameterDesc.
    //   * Sync occurs using the discovered
    //     javaTypes and the javaTypes of the Method
    //     parameters
    //
    // B) Deployment with no wsdd OperationDesc info (non-skeleton):
    //   * Implementation Class introspected to build
    //     OperationDesc/ParameterDesc.
    //   * ParameterDesc is known via introspection.
    //   * ParameterDesc are discovered using javaType
    //     and TypeMappingRegistry.
    //   * Sync occurs using the introspected
    //     javaTypes and the javaTypes of the Method
    //     parameters
    //
    // C) Deployment with wsdd (skeleton):
    //   * OperationDesc/ParameterDesc loaded from the Skeleton
    //   * In this scenario the ParameterDescs' already
    //     have javaTypes (see E below).
    //   * Sync occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // D) Commandline Java2WSDL loading non-Skeleton Class/Interface
    //   * Class/Interface introspected to build
    //     OperationDesc/ParameterDesc.
    //   * The javaTypes of the ParameterDesc are set using introspection.
    //   * typeQNames are determined for built-in types using
    //     from the default TypeMappingRegistry.  Other
    //     typeQNames are guessed from the javaType.  Note
    //     that there is no loaded TypeMappingRegistry.
    //   * Sync occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // E) Commandline Java2WSDL loading Skeleton Class
    //   * OperationDesc/ParameterDesc loaded from Skeleton
    //   * Each ParameterDesc has an appropriate typeQName
    //   * Each ParameterDesc also has a javaType, which is
    //     essential for sync'ing up with the
    //     method since there is no loaded TypeMappingRegistry.
    //   * Syncronization occurs using the ParameterDesc
    //     javaTypes and the javaTypes of the Method
    //     parameters.
    //
    // So in each scenario, the ultimate sync'ing occurs
    // using the javaTypes of the ParameterDescs and the
    // javaTypes of the Method parameters.
    //
    // ------------------------------------------------

    // If we're already mapped to a Java method, no need to do anything.
    if (oper.getMethod() != null)
        return;

    // Find the method.  We do this once for each Operation.

    Method[] methods = getMethods(implClass);
    // A place to keep track of possible matches
    Method possibleMatch = null;

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (Modifier.isPublic(method.getModifiers()) && method.getName().equals(oper.getName())
                && method2OperationMap.get(method) == null) {

            if (style == Style.MESSAGE) {
                int messageOperType = checkMessageMethod(method);
                if (messageOperType == OperationDesc.MSG_METHOD_NONCONFORMING)
                    continue;
                if (messageOperType == -1) {
                    throw new InternalException(
                            "Couldn't match method to any of the allowable message-style patterns!");
                }
                oper.setMessageOperationStyle(messageOperType);

                // Don't bother checking params if we're message style
                possibleMatch = method;
                break;
            }

            // Check params
            Class[] paramTypes = method.getParameterTypes();
            if (paramTypes.length != oper.getNumParams())
                continue;

            int j;
            boolean conversionNecessary = false;
            for (j = 0; j < paramTypes.length; j++) {
                Class type = paramTypes[j];
                Class actualType = type;
                if (Holder.class.isAssignableFrom(type)) {
                    actualType = JavaUtils.getHolderValueType(type);
                }
                ParameterDesc param = oper.getParameter(j);
                QName typeQName = param.getTypeQName();
                if (typeQName == null) {
                    // No typeQName is available.  Set it using
                    // information from the actual type.
                    // (Scenarios B and D)
                    // There is no need to try and match with
                    // the Method parameter javaType because
                    // the ParameterDesc is being constructed
                    // by introspecting the Method.
                    typeQName = getTypeMapping().getTypeQName(actualType);
                    param.setTypeQName(typeQName);
                } else {
                    // A type qname is available.
                    // Ensure that the ParameterDesc javaType
                    // is convertable to the Method parameter type
                    //
                    // Use the available javaType (Scenarios C and E)
                    // or get one from the TMR (Scenario A).
                    Class paramClass = param.getJavaType();
                    if (paramClass != null && JavaUtils.getHolderValueType(paramClass) != null) {
                        paramClass = JavaUtils.getHolderValueType(paramClass);
                    }
                    if (paramClass == null) {
                        paramClass = getTypeMapping().getClassForQName(param.getTypeQName(), type);
                    }

                    if (paramClass != null) {
                        // This is a match if the paramClass is somehow
                        // convertable to the "real" parameter type.  If not,
                        // break out of this loop.
                        if (!JavaUtils.isConvertable(paramClass, actualType)) {
                            break;
                        }

                        if (!actualType.isAssignableFrom(paramClass)) {
                            // This doesn't fit without conversion
                            conversionNecessary = true;
                        }
                    }
                }
                // In all scenarios the ParameterDesc javaType is set to
                // match the javaType in the corresponding parameter.
                // This is essential.
                param.setJavaType(type);
            }

            if (j != paramTypes.length) {
                // failed.
                continue;
            }

            // This is our latest possibility
            possibleMatch = method;

            // If this is exactly it, stop now.  Otherwise keep looking
            // just in case we find a better match.
            if (!conversionNecessary) {
                break;
            }

        }
    }

    // At this point, we may or may not have a possible match.
    // FIXME : Should we prefer an exact match from a base class over
    //         a with-conversion match from the target class?  If so,
    //         we'll need to change the logic below.
    if (possibleMatch != null) {
        Class returnClass = possibleMatch.getReturnType();
        oper.setReturnClass(returnClass);

        QName returnType = oper.getReturnType();
        if (returnType == null) {
            oper.setReturnType(getTypeMapping().getTypeQName(returnClass));
        }

        // Do the faults
        createFaultMetadata(possibleMatch, oper);

        oper.setMethod(possibleMatch);
        method2OperationMap.put(possibleMatch, oper);
        return;
    }

    // Didn't find a match.  Try the superclass, if appropriate
    Class superClass = implClass.getSuperclass();
    if (superClass != null && !superClass.getName().startsWith("java.")
            && !superClass.getName().startsWith("javax.")
            && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
        syncOperationToClass(oper, superClass);
    }

    // Exception if sync fails to find method for operation
    if (oper.getMethod() == null) {
        InternalException ie = new InternalException(
                Messages.getMessage("serviceDescOperSync00", oper.getName(), implClass.getName()));
        throw ie;
    }
}

From source file:org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils.java

public static boolean isPublic(Field field) {
    return Modifier.isPublic(field.getModifiers());
}

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/* w w  w .j  ava2s .  c  o  m*/
 * @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:org.apache.calcite.test.CalciteAssert.java

/** Finds a non-static method based on its target, name and arguments.
 * Throws if not found. *//*from  w  w  w.  ja  va2s.c  om*/
static Method method(Object o, String methodName, Object[] args) {
    for (Class<?> aClass = o.getClass();;) {
        loop: for (Method method1 : aClass.getMethods()) {
            if (method1.getName().equals(methodName) && method1.getParameterTypes().length == args.length
                    && Modifier.isPublic(method1.getDeclaringClass().getModifiers())) {
                for (Pair<Object, Class> pair : Pair.zip(args, (Class[]) method1.getParameterTypes())) {
                    if (!pair.right.isInstance(pair.left)) {
                        continue loop;
                    }
                }
                return method1;
            }
        }
        if (aClass.getSuperclass() != null && aClass.getSuperclass() != Object.class) {
            aClass = aClass.getSuperclass();
        } else {
            final Class<?>[] interfaces = aClass.getInterfaces();
            if (interfaces.length > 0) {
                aClass = interfaces[0];
            } else {
                break;
            }
        }
    }
    throw new AssertionError("method " + methodName + " not found");
}

From source file:org.codehaus.griffon.commons.GriffonClassUtils.java

/**
 * Work out if the specified object has a public field with the name supplied.
 *
 * @param obj/*from   ww w  .java 2 s  . c o m*/
 * @param name
 * @return True if a public field with the name exists
 */
public static boolean isPublicField(Object obj, String name) {
    Class clazz = obj.getClass();
    Field f = null;
    try {
        f = clazz.getDeclaredField(name);
        return Modifier.isPublic(f.getModifiers());
    } catch (NoSuchFieldException e) {
        return false;
    }
}

From source file:org.evosuite.testcarver.testcase.EvoTestCaseCodeGenerator.java

private boolean hasDefaultConstructor(final Class<?> clazz) {
    for (final Constructor<?> c : clazz.getConstructors()) {
        if (c.getParameterTypes().length == 0 && Modifier.isPublic(c.getModifiers())) {
            return true;
        }//from   w ww .jav  a  2 s.co m
    }

    return false;
}

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   w  w  w . j av a 2 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();
}