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.lucidtechnics.blackboard.TargetConstructor.java

private final static List findMutatorMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne && isPublic;
        }//from   w w w.ja va2 s  .c  om
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given field accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active)./*from ww  w  . ja v  a  2 s .c o m*/
 * @param field the field to make accessible
 * @see java.lang.reflect.Field#setAccessible
 */
public static void makeAccessible(Field field) {
    if ((!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())
            || Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
        field.setAccessible(true);
    }
}

From source file:name.yumaa.ChromeLogger4J.java

/**
 * Returns a nicely formatted key of the field or method name
 * @param mod    .getModifiers()/*from w ww .  j  av a2 s.  com*/
 * @param end    key ending
 * @return class member keys, converted to string
 */
private String getKey(int mod, String end) {
    StringBuilder key = new StringBuilder("");
    if (Modifier.isPublic(mod))
        key.append("public ");
    if (Modifier.isPrivate(mod))
        key.append("private ");
    if (Modifier.isProtected(mod))
        key.append("protected ");
    if (Modifier.isStatic(mod))
        key.append("static ");
    if (Modifier.isTransient(mod))
        key.append("transient ");
    if (Modifier.isVolatile(mod))
        key.append("volatile ");
    if (Modifier.isFinal(mod))
        key.append("final ");
    if (Modifier.isSynchronized(mod))
        key.append("synchronized ");
    return key.append(end).toString();
}

From source file:com.strandls.alchemy.rest.client.AlchemyRestClientFactoryTest.java

/**
 * Test method for/*from w ww  . j a v  a  2s .  c o  m*/
 * {@link com.strandls.alchemy.rest.client.AlchemyRestClientFactory#getInstance(java.lang.Class, java.lang.String, javax.ws.rs.client.Client)}
 * .
 *
 * Test get and post methods with a combination of parameter types (query,
 * path, header, cookie, matrix)
 *
 * @throws Exception
 */
@Test
public void testGetInstanceStub() throws Exception {
    final TestWebserviceWithPathStub service = clientFactory.getInstance(TestWebserviceWithPathStub.class);

    final Random r = new Random();

    final int[] args = new int[] { r.nextInt(), r.nextInt(), r.nextInt() };
    @SuppressWarnings("unchecked")
    final Set<Method> methods = ReflectionUtils.getAllMethods(TestWebserviceWithPathStub.class,
            new Predicate<Method>() {
                @Override
                public boolean apply(final Method input) {
                    return Modifier.isPublic(input.getModifiers());
                }
            });

    for (final Method method : methods) {
        System.out.println("Invoking : " + method);
        if (method.getParameterTypes().length == 3) {
            assertArrayEquals("Invocation failed on " + method, args,
                    (int[]) method.invoke(service, args[0], args[1], args[2]));
        } else {
            assertArrayEquals("Invocation failed on " + method, args, (int[]) method.invoke(service, args));
        }
        System.out.println("Done invoking : " + method);
    }
}

From source file:com.almende.eve.protocol.jsonrpc.JSONRpc.java

/**
 * Check whether a method is available for JSON-RPC calls. This is the case
 * when it is public, has named parameters, and has a public or private @Access
 * annotation/*  www .  jav a 2s.c o  m*/
 * 
 * @param method
 *            the method
 * @param destination
 *            the destination
 * @param requestParams
 *            the request params
 * @param auth
 *            the auth
 * @return available
 */
private static boolean isAvailable(final AnnotatedMethod method, final Object destination,
        final RequestParams requestParams, final Authorizor auth) {

    if (method == null) {
        return false;
    }
    Access methodAccess = method.getAnnotation(Access.class);
    if (destination != null
            && !method.getActualMethod().getDeclaringClass().isAssignableFrom(destination.getClass())) {
        return false;
    }
    final int mod = method.getActualMethod().getModifiers();
    if (!(Modifier.isPublic(mod) && hasNamedParams(method, requestParams))) {
        return false;
    }

    final Access classAccess = AnnotationUtil
            .get(destination != null ? destination.getClass() : method.getActualMethod().getDeclaringClass())
            .getAnnotation(Access.class);
    if (methodAccess == null) {
        methodAccess = classAccess;
    }
    if (methodAccess == null) {
        // New default: UNAVAILABLE!
        return false;
    }
    if (methodAccess.value() == AccessType.UNAVAILABLE) {
        return false;
    }

    if (methodAccess.value() == AccessType.PRIVATE) {
        return auth != null ? auth.onAccess(requestParams.get(Sender.class).toString(), methodAccess.tag())
                : false;
    }
    if (methodAccess.value() == AccessType.SELF) {
        return auth != null ? auth.isSelf(requestParams.get(Sender.class).toString()) : false;
    }
    return true;
}

From source file:es.caib.zkib.jxpath.util.ValueUtils.java

/**
 * Return an accessible method (that is, one that can be invoked via
 * reflection) that implements the specified Method.  If no such method
 * can be found, return <code>null</code>.
 *
 * @param method The method that we wish to call
 * @return Method/*from  w w  w.  j  a  v  a2s. c o  m*/
 */
public static Method getAccessibleMethod(Method method) {

    // Make sure we have a method to check
    if (method == null) {
        return (null);
    }

    // If the requested method is not public we cannot call it
    if (!Modifier.isPublic(method.getModifiers())) {
        return (null);
    }

    // If the declaring class is public, we are done
    Class clazz = method.getDeclaringClass();
    if (Modifier.isPublic(clazz.getModifiers())) {
        return (method);
    }

    String name = method.getName();
    Class[] parameterTypes = method.getParameterTypes();
    while (clazz != null) {
        // Check the implemented interfaces and subinterfaces
        Method aMethod = getAccessibleMethodFromInterfaceNest(clazz, name, parameterTypes);
        if (aMethod != null) {
            return aMethod;
        }

        clazz = clazz.getSuperclass();
        if (clazz != null && Modifier.isPublic(clazz.getModifiers())) {
            try {
                return clazz.getDeclaredMethod(name, parameterTypes);
            } catch (NoSuchMethodException e) { //NOPMD
                //ignore
            }
        }
    }
    return null;
}

From source file:br.com.lucasisrael.regra.reflections.TratamentoReflections.java

/**
 * Make the given method accessible, explicitly setting it accessible if
 * necessary. The {@code setAccessible(true)} method is only called
 * when actually necessary, to avoid unnecessary conflicts with a JVM
 * SecurityManager (if active).//from ww w.j av a 2  s .c  om
 * @param method the method to make accessible
 * @see java.lang.reflect.Method#setAccessible
 */
public static void makeAccessible(Method method) {
    if ((!Modifier.isPublic(method.getModifiers())
            || !Modifier.isPublic(method.getDeclaringClass().getModifiers())) && !method.isAccessible()) {
        method.setAccessible(true);
    }
}

From source file:com.lucidtechnics.blackboard.TargetConstructor.java

private final static List findOtherPublicMethods(Class _class) {
    List methodList = new ArrayList();

    Enhancer.getMethods(_class, null, methodList);

    Predicate mutatorPredicate = new Predicate() {
        public boolean evaluate(Object _object) {
            Method method = (Method) _object;

            boolean startsWithSet = (method.getName().startsWith("set") == true);
            boolean returnTypeIsVoid = ("void".equals(method.getReturnType().getName()) == true);
            boolean parameterTypeCountIsOne = (method.getParameterTypes().length == 1);
            boolean isPublic = (Modifier.isPublic(method.getModifiers()) == true);

            return ((startsWithSet && returnTypeIsVoid && parameterTypeCountIsOne) == false) && isPublic;
        }/* ww  w  .  ja  va  2s . c  o  m*/
    };

    CollectionUtils.filter(methodList, mutatorPredicate);

    return methodList;
}

From source file:de.codesourcery.springmass.springmass.SimulationParamsBuilder.java

private boolean isPartOfPublicInterface(Method m) {
    final int mods = m.getModifiers();
    if (Modifier.isStatic(mods) || Modifier.isAbstract(mods) || Modifier.isNative(mods)
            || !Modifier.isPublic(mods)) {
        return false;
    }//from  ww  w . j a  v  a 2s . co  m
    return true;
}

From source file:org.enerj.apache.commons.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./*  ww  w . java2  s .  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;
}