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:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Field f, Class<?> ownerClass) {

    // TODO we could enable some methods from Object, like getClass
    if (f.getDeclaringClass().equals(java.lang.Object.class))
        return false;// handled here to avoid printing reasons

    if (f.getDeclaringClass().equals(java.lang.Thread.class))
        return false;// handled here to avoid printing reasons

    if (!Properties.USE_DEPRECATED && f.isAnnotationPresent(Deprecated.class)) {
        logger.debug("Skipping deprecated field {}", f.getName());
        return false;
    }/*from   ww w .  j  a v a 2 s .c  o m*/

    if (f.isSynthetic()) {
        logger.debug("Skipping synthetic field {}", f.getName());
        return false;
    }

    if (f.getName().startsWith("ajc$")) {
        logger.debug("Skipping AspectJ field {}", f.getName());
        return false;
    }

    if (!f.getType().equals(String.class) && !canUse(f.getType())) {
        return false;
    }

    if (Modifier.isPublic(f.getModifiers())) {
        // It may still be the case that the field is defined in a non-visible superclass of the class
        // we already know we can use. In that case, the compiler would be fine with accessing the 
        // field, but reflection would start complaining about IllegalAccess!
        // Therefore, we set the field accessible to be on the safe side
        makeAccessible(f);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(f.getModifiers())) {
        //              && !Modifier.isProtected(f.getModifiers())) {
        String packageName = ClassUtils.getPackageName(ownerClass);

        String declaredPackageName = ClassUtils.getPackageName(f.getDeclaringClass());

        if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) {
            makeAccessible(f);
            return true;
        }
    }

    return false;
}

From source file:com.github.wshackle.java4cpp.J4CppMain.java

private static boolean checkMethod(Method m, List<Class> classes) {
    if (m.getDeclaringClass().getName().equals(m.getName())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " method same as classname.");
        }//from  w  w w .  j a  va 2  s  . com
        return false;
    }
    if (m.getDeclaringClass().getName().endsWith("." + m.getName())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " method same as classname.");
        }
        return false;
    }
    if (m.isSynthetic()) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " isSynthetic.");
        }
        return false;
    }
    if (!Modifier.isPublic(m.getModifiers())) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " not public");
        }
        return false;
    }
    if (!checkClass(m.getReturnType(), classes)) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " return type not in classes list.");
        }
        return false;
    }
    boolean ret = checkParameters(m.getParameterTypes(), classes);
    if (!ret) {
        if (verbose) {
            System.out.println("checkMethod skipping " + m + " a parameter type is not in classes list");
        }
    }
    return ret;
}

From source file:org.apache.poi.util.MethodUtils.java

public static <T> Constructor<T> getMatchingAccessibleConstructor(Class<T> clazz, Class[] parameterTypes) {
    // trace logging
    Log log = LogFactory.getLog(MethodUtils.class);
    MethodDescriptor md = new MethodDescriptor(clazz, "dummy", parameterTypes, false);

    // see if we can find the method directly
    // most of the time this works and it's much faster
    try {/* w w  w.j a  v a  2s.com*/
        Constructor<T> constructor = clazz.getConstructor(parameterTypes);
        if (log.isTraceEnabled()) {
            log.trace("Found straight match: " + constructor);
            log.trace("isPublic:" + Modifier.isPublic(constructor.getModifiers()));
        }

        setMethodAccessible(constructor); // Default access superclass workaround

        return constructor;

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

    // search through all methods 
    int paramSize = parameterTypes.length;
    Constructor<T> bestMatch = null;
    Constructor<?>[] constructors = clazz.getConstructors();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (int i = 0, size = constructors.length; i < size; i++) {
        // compare parameters
        Class[] methodsParams = constructors[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
                Constructor<T> cons = (Constructor<T>) constructors[i];
                myCost = getTotalTransformationCost(parameterTypes, cons.getParameterTypes());
                if (myCost < bestMatchCost) {
                    bestMatch = cons;
                    bestMatchCost = myCost;
                }
            }
        }
    }
    if (bestMatch == null) {
        // didn't find a match
        log.trace("No match found.");
    }

    return bestMatch;
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>//from   w  w w .  j a v a2s  .co m
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified method, by scanning through all
 * implemented interfaces and subinterfaces. If no such method can be found,
 * return <code>null</code>.
 * </p>
 *
 * <p>
 * There isn't any good reason why this method must be private. It is
 * because there doesn't seem any reason why other classes should call this
 * rather than the higher level methods.
 * </p>
 *
 * @param clazz
 *            Parent class for the interfaces to be checked
 * @param methodName
 *            Method name of the method we wish to call
 * @param parameterTypes
 *            The parameter type signatures
 */
private static Method getAccessibleMethodFromInterfaceNest(Class<?> clazz, final String methodName,
        final Class<?>[] parameterTypes) {

    Method method = null;

    // Search up the superclass chain
    for (; clazz != null; clazz = clazz.getSuperclass()) {

        // Check the implemented interfaces of the parent class
        final Class<?>[] interfaces = clazz.getInterfaces();
        for (int i = 0; i < interfaces.length; i++) {

            // Is this interface public?
            if (!Modifier.isPublic(interfaces[i].getModifiers())) {
                continue;
            }

            // Does the method exist on this interface?
            try {
                method = interfaces[i].getDeclaredMethod(methodName, parameterTypes);
            } catch (final NoSuchMethodException e) {
                /*
                 * Swallow, if no method is found after the loop then this
                 * method returns null.
                 */
            }
            if (method != null) {
                return method;
            }

            // Recursively check our parent interfaces
            method = getAccessibleMethodFromInterfaceNest(interfaces[i], methodName, parameterTypes);
            if (method != null) {
                return method;
            }

        }

    }

    // We did not find anything
    return null;
}

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

/**
 * Recursive helper class for loadServiceDescByIntrospection
 *//*w  ww. j  ava 2  s . com*/
private void loadServiceDescByIntrospectionRecursive(Class implClass) {
    if (Skeleton.class.equals(implClass)) {
        return;
    }

    Method[] methods = getMethods(implClass);

    for (int i = 0; i < methods.length; i++) {
        if (Modifier.isPublic(methods[i].getModifiers()) && !isServiceLifeCycleMethod(implClass, methods[i])) {
            getSyncedOperationsForName(implClass, methods[i].getName());
        }
    }

    if (implClass.isInterface()) {
        Class[] superClasses = implClass.getInterfaces();
        for (int i = 0; i < superClasses.length; i++) {
            Class superClass = superClasses[i];
            if (!superClass.getName().startsWith("java.") && !superClass.getName().startsWith("javax.")
                    && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
                loadServiceDescByIntrospectionRecursive(superClass);
            }
        }
    } else {
        Class superClass = implClass.getSuperclass();
        if (superClass != null && !superClass.getName().startsWith("java.")
                && !superClass.getName().startsWith("javax.")
                && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
            loadServiceDescByIntrospectionRecursive(superClass);
        }
    }
}

From source file:org.apache.hadoop.yarn.api.TestPBImplRecords.java

private <R> Map<String, GetSetPair> getGetSetPairs(Class<R> recordClass) throws Exception {
    Map<String, GetSetPair> ret = new HashMap<String, GetSetPair>();
    Method[] methods = recordClass.getDeclaredMethods();
    // get all get methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];/*www .  j a  v a  2  s . c  o  m*/
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.equals("getProto")) {
                continue;
            }
            if ((name.length() > 3) && name.startsWith("get") && (m.getParameterTypes().length == 0)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericReturnType();
                GetSetPair p = ret.get(propertyName);
                if (p == null) {
                    p = new GetSetPair();
                    p.propertyName = propertyName;
                    p.type = valueType;
                    p.getMethod = m;
                    ret.put(propertyName, p);
                } else {
                    Assert.fail("Multiple get method with same name: " + recordClass + p.propertyName);
                }
            }
        }
    }
    // match get methods with set methods
    for (int i = 0; i < methods.length; i++) {
        Method m = methods[i];
        int mod = m.getModifiers();
        if (m.getDeclaringClass().equals(recordClass) && Modifier.isPublic(mod) && (!Modifier.isStatic(mod))) {
            String name = m.getName();
            if (name.startsWith("set") && (m.getParameterTypes().length == 1)) {
                String propertyName = name.substring(3);
                Type valueType = m.getGenericParameterTypes()[0];
                GetSetPair p = ret.get(propertyName);
                if (p != null && p.type.equals(valueType)) {
                    p.setMethod = m;
                }
            }
        }
    }
    // exclude incomplete get/set pair, and generate test value
    Iterator<Entry<String, GetSetPair>> itr = ret.entrySet().iterator();
    while (itr.hasNext()) {
        Entry<String, GetSetPair> cur = itr.next();
        GetSetPair gsp = cur.getValue();
        if ((gsp.getMethod == null) || (gsp.setMethod == null)) {
            LOG.info(String.format("Exclude protential property: %s\n", gsp.propertyName));
            itr.remove();
        } else {
            LOG.info(String.format("New property: %s type: %s", gsp.toString(), gsp.type));
            gsp.testValue = genTypeValue(gsp.type);
            LOG.info(String.format(" testValue: %s\n", gsp.testValue));
        }
    }
    return ret;
}

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  . j  ava 2  s .  co  m*/
 * @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.glaf.core.util.ReflectUtils.java

public static void setFieldValue(Object target, String name, Class<?> type, Object value) {
    if (target == null || StringUtils.isEmpty(name)
            || (value != null && !type.isAssignableFrom(value.getClass()))) {
        return;// ww w . ja  v  a2s  .  c om
    }
    Class<?> clazz = target.getClass();
    try {
        Method method = clazz
                .getDeclaredMethod("set" + Character.toUpperCase(name.charAt(0)) + name.substring(1), type);
        if (!Modifier.isPublic(method.getModifiers())) {
            method.setAccessible(true);
        }
        method.invoke(target, value);
    } catch (Exception ex) {
        if (LogUtils.isDebug()) {
            logger.debug(ex);
        }
        try {
            Field field = clazz.getDeclaredField(name);
            if (!Modifier.isPublic(field.getModifiers())) {
                field.setAccessible(true);
            }
            field.set(target, value);
        } catch (Exception e) {
            if (LogUtils.isDebug()) {
                logger.debug(e);
            }
        }
    }
}

From source file:eu.qualityontime.commons.MethodUtils.java

/**
 * <p>/*from ww  w  .  j  a  va  2s .  com*/
 * 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. In other words, it finds a method
 * with the given name that will take the parameters given.
 * </p>
 *
 * <p>
 * This method is slightly undeterministic 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(final Class<?> clazz, final String methodName,
        final Class<?>[] parameterTypes) {
    // trace logging
    final Log log = LogFactory.getLog(MethodUtils.class);
    if (log.isTraceEnabled()) {
        log.trace("Matching name=" + methodName + " on " + clazz);
    }
    final 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 (final NoSuchMethodException e) {
        /* SWALLOW */ }

    // search through all methods
    final int paramSize = parameterTypes.length;
    Method bestMatch = null;
    final Method[] methods = clazz.getMethods();
    float bestMatchCost = Float.MAX_VALUE;
    float myCost = Float.MAX_VALUE;
    for (final Method method2 : methods) {
        if (method2.getName().equals(methodName)) {
            // log some trace information
            if (log.isTraceEnabled()) {
                log.trace("Found matching name:");
                log.trace(method2);
            }

            // compare parameters
            final Class<?>[] methodsParams = method2.getParameterTypes();
            final 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
                    final Method method = getAccessibleMethod(clazz, method2);
                    if (method != null) {
                        if (log.isTraceEnabled()) {
                            log.trace(method + " accessible version of " + method2);
                        }
                        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:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Method m, Class<?> ownerClass) {

    if (m.isBridge()) {
        logger.debug("Excluding bridge method: {}", m.toString());
        return false;
    }/*from  w  w w.  j av  a2  s .c  o  m*/

    if (m.isSynthetic()) {
        logger.debug("Excluding synthetic method: {}", m.toString());
        return false;
    }

    if (!Properties.USE_DEPRECATED && m.isAnnotationPresent(Deprecated.class)) {
        logger.debug("Excluding deprecated method {}", m.getName());
        return false;
    }

    if (m.isAnnotationPresent(Test.class)) {
        logger.debug("Excluding test method {}", m.getName());
        return false;
    }

    if (m.isAnnotationPresent(EvoSuiteExclude.class)) {
        logger.debug("Excluding method with exclusion annotation {}", m.getName());
        return false;
    }

    if (m.getDeclaringClass().equals(java.lang.Object.class)) {
        return false;
    }

    if (!m.getReturnType().equals(String.class) && !canUse(m.getReturnType())) {
        return false;
    }

    if (m.getDeclaringClass().equals(Enum.class)) {
        return false;
        /*
        if (m.getName().equals("valueOf") || m.getName().equals("values")
         || m.getName().equals("ordinal")) {
           logger.debug("Excluding valueOf for Enum " + m.toString());
           return false;
        }
        // Skip compareTo on enums (like Randoop)
        if (m.getName().equals("compareTo") && m.getParameterTypes().length == 1
         && m.getParameterTypes()[0].equals(Enum.class))
           return false;
           */
    }

    if (m.getDeclaringClass().equals(java.lang.Thread.class))
        return false;

    // Hashcode only if we need to cover it
    if (m.getName().equals("hashCode") && !m.getDeclaringClass().equals(Properties.getTargetClass()))
        return false;

    // Randoop special case: just clumps together a bunch of hashCodes, so skip it
    if (m.getName().equals("deepHashCode") && m.getDeclaringClass().equals(Arrays.class))
        return false;

    // Randoop special case: differs too much between JDK installations
    if (m.getName().equals("getAvailableLocales"))
        return false;

    if (m.getName().equals(ClassResetter.STATIC_RESET)) {
        logger.debug("Ignoring static reset class");
        return false;
    }

    if (isForbiddenNonDeterministicCall(m)) {
        return false;
    }

    if (!Properties.CONSIDER_MAIN_METHODS && m.getName().equals("main") && Modifier.isStatic(m.getModifiers())
            && Modifier.isPublic(m.getModifiers())) {
        logger.debug("Ignoring static main method ");
        return false;
    }

    /*
    if(m.getTypeParameters().length > 0) {
       logger.debug("Cannot handle generic methods at this point");
       if(m.getDeclaringClass().equals(Properties.getTargetClass())) {
    LoggingUtils.getEvoLogger().info("* Skipping method "+m.getName()+": generic methods are not handled yet");
       }
       return false;
    }
    */

    // If default or
    if (Modifier.isPublic(m.getModifiers())) {
        makeAccessible(m);
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(m.getModifiers())) {
        //              && !Modifier.isProtected(m.getModifiers())) {
        String packageName = ClassUtils.getPackageName(ownerClass);
        String declaredPackageName = ClassUtils.getPackageName(m.getDeclaringClass());
        if (packageName.equals(Properties.CLASS_PREFIX) && packageName.equals(declaredPackageName)) {
            makeAccessible(m);
            return true;
        }
    }

    return false;
}