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.apache.pig.JVMReuseManager.java

public void registerForStaticDataCleanup(Class<?> clazz) {
    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(StaticDataCleanup.class)) {
            if (!(Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers()))) {
                throw new RuntimeException("Method " + method.getName() + " in class " + clazz.getName()
                        + "should be public and static as it is annotated with  ");
            }//from w ww.j  a v a 2 s  . com
            LOG.debug("Method " + method.getName() + " in class " + method.getDeclaringClass()
                    + " registered for static data cleanup");
            instance.cleanupMethods.add(method);
        }
    }
}

From source file:com.jetyun.pgcd.rpc.reflect.ClassAnalyzer.java

/**
 * Analyze a class and create a ClassData object containing all of the
 * public methods (both static and non-static) in the class.
 * /* w w  w  .jav a  2s. c o  m*/
 * @param clazz
 *            class to be analyzed.
 * 
 * @return a ClassData object containing all the public static and
 *         non-static methods that can be invoked on the class.
 */
private static ClassData analyzeClass(Class clazz) {
    log.info("analyzing " + clazz.getName());
    Method methods[] = clazz.getMethods();
    ClassData cd = new ClassData();
    cd.clazz = clazz;

    // Create temporary method map
    HashMap staticMethodMap = new HashMap();
    HashMap methodMap = new HashMap();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.getDeclaringClass() == Object.class) {
            continue;
        }
        int mod = methods[i].getModifiers();
        if (!Modifier.isPublic(mod)) {
            continue;
        }
        Class param[] = method.getParameterTypes();

        // don't count locally resolved args
        int argCount = 0;
        for (int n = 0; n < param.length; n++) {
            if (LocalArgController.isLocalArg(param[n])) {
                continue;
            }
            argCount++;
        }

        MethodKey mk = new MethodKey(method.getName(), argCount);
        ArrayList marr = (ArrayList) methodMap.get(mk);
        if (marr == null) {
            marr = new ArrayList();
            methodMap.put(mk, marr);
        }
        marr.add(method);
        if (Modifier.isStatic(mod)) {
            marr = (ArrayList) staticMethodMap.get(mk);
            if (marr == null) {
                marr = new ArrayList();
                staticMethodMap.put(mk, marr);
            }
            marr.add(method);
        }
    }
    cd.methodMap = new HashMap();
    cd.staticMethodMap = new HashMap();
    // Convert ArrayLists to arrays
    Iterator i = methodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.methodMap.put(mk, marr.get(0));
        } else {
            cd.methodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    i = staticMethodMap.entrySet().iterator();
    while (i.hasNext()) {
        Map.Entry entry = (Map.Entry) i.next();
        MethodKey mk = (MethodKey) entry.getKey();
        ArrayList marr = (ArrayList) entry.getValue();
        if (marr.size() == 1) {
            cd.staticMethodMap.put(mk, marr.get(0));
        } else {
            cd.staticMethodMap.put(mk, marr.toArray(new Method[0]));
        }
    }
    return cd;
}

From source file:org.zht.framework.util.ZBeanUtil.java

private static void copy(Object source, Object target, Boolean ignorNull, Class<?> editable,
        String... ignoreProperties) throws BeansException {

    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    Class<?> actualEditable = target.getClass();
    if (editable != null) {
        if (!editable.isInstance(target)) {
            throw new IllegalArgumentException("Target class [" + target.getClass().getName()
                    + "] not assignable to Editable class [" + editable.getName() + "]");
        }/*from w w  w  .  ja v a2  s  . co m*/
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

    for (PropertyDescriptor targetPd : targetPds) {
        Method writeMethod = targetPd.getWriteMethod();
        if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null) {
                Method readMethod = sourcePd.getReadMethod();
                if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0],
                        readMethod.getReturnType())) {
                    try {
                        if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                            readMethod.setAccessible(true);
                        }
                        Object value = readMethod.invoke(source);
                        if (ignorNull != null && ignorNull) {
                            if (value != null && (!"[]".equals(value.toString()))) {// ?
                                if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                    writeMethod.setAccessible(true);
                                }
                                writeMethod.invoke(target, value);
                            }
                        } else {
                            if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                                writeMethod.setAccessible(true);
                            }
                            writeMethod.invoke(target, value);
                        }

                    } catch (Throwable ex) {
                        throw new FatalBeanException(
                                "Could not copy property '" + targetPd.getName() + "' from source to target",
                                ex);
                    }
                }
            }
        }
    }
}

From source file:org.evosuite.setup.TestUsageChecker.java

public static boolean canUse(Constructor<?> c) {

    if (c.isSynthetic()) {
        return false;
    }/*from  w w  w.ja v  a2 s . com*/

    // synthetic constructors are OK
    if (Modifier.isAbstract(c.getDeclaringClass().getModifiers()))
        return false;

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

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

    if (c.getDeclaringClass().isAnonymousClass())
        return false;

    if (c.getDeclaringClass().isLocalClass()) {
        logger.debug("Skipping constructor of local class " + c.getName());
        return false;
    }

    if (c.getDeclaringClass().isMemberClass() && !TestUsageChecker.canUse(c.getDeclaringClass()))
        return false;

    if (!Properties.USE_DEPRECATED && c.isAnnotationPresent(Deprecated.class)) {
        final Class<?> targetClass = Properties.getTargetClassAndDontInitialise();
        if (Properties.hasTargetClassBeenLoaded() && !c.getDeclaringClass().equals(targetClass)) {
            logger.debug("Excluding deprecated constructor " + c.getName());
            return false;
        }
    }

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

    if (Modifier.isPublic(c.getModifiers())) {
        TestClusterUtils.makeAccessible(c);
        return true;
    }

    for (java.lang.reflect.Type paramType : c.getGenericParameterTypes()) {
        if (!canUse(paramType))
            return false;
    }

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

    return false;
}

From source file:py.una.pol.karaku.test.test.ValidationMessagesTest.java

@Test
public void testConstants() {

    ReflectionUtils.doWithFields(ValidationMessages.class, new FieldCallback() {

        @Override//from  w w  w .  j  av  a  2  s  .c  om
        public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {

            String value = (String) field.get(null);
            assertNotNull(value);
            assertTrue("Key: " + value + " not found", keys.contains(value));
        }
    }, new FieldFilter() {

        @Override
        public boolean matches(Field field) {

            int modifiers = field.getModifiers();
            return Modifier.isStatic(modifiers) && !Modifier.isTransient(modifiers)
                    && Modifier.isPublic(modifiers);
        }
    });
}

From source file:org.evosuite.setup.TestClusterUtils.java

public static void makeAccessible(Field field) {
    if (!Modifier.isPublic(field.getModifiers())
            || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
        field.setAccessible(true);/* w ww . j a v a 2  s .com*/
    }
}

From source file:guru.qas.martini.annotation.MartiniAnnotationCallback.java

protected void process(Method method, A annotation) {
    checkState(Modifier.isPublic(method.getModifiers()), "Method is not public: %s", method);

    String regex = getValue(annotation).trim();
    String annotationName = annotationClass.getSimpleName();
    checkState(!regex.isEmpty(), "@%s requires non-empty regex values.", annotationName);
    checkState(!regularExpressions.contains(regex), "Multiple methods found for @%s regex \"%s\"",
            annotationName, regex);/*from  w  ww. j a  va2 s  .  c o  m*/
    Pattern pattern = Pattern.compile(regex);
    regularExpressions.add(regex);

    String name = String.format("%s%s", annotationName.toLowerCase(), atomicInteger.getAndIncrement());

    DefaultStep step = new DefaultStep(annotationName, pattern, method);
    beanFactory.registerSingleton(name, step);
}

From source file:com.dianping.squirrel.client.util.ClassUtils.java

public static <T> Constructor<T> getDeclaredConstructor(Constructor<T> ctor) {
    if (ctor == null) {
        return (null);
    }//from   ww w  .  j ava  2s .  com
    Class<T> clazz = ctor.getDeclaringClass();
    if (Modifier.isPublic(clazz.getModifiers())) {
        return (ctor);
    }
    return null;

}

From source file:org.araneaframework.backend.util.BeanMapper.java

/**
 * Returns <code>List&lt;String&gt;</code>- the <code>List</code> of VO
 *         field names.//from  w w  w . ja  va 2s  .  com
 * @return <code>List&lt;String&gt;</code>- the <code>List</code> of VO
 *         field names.
 */
public List getBeanFields() {
    List result = new ArrayList();

    Method[] voMethods = voClass.getMethods();
    for (int i = 0; i < voMethods.length; i++) {
        Method voMethod = voMethods[i];
        //Checking that method may be a valid getter method
        if (Modifier.isPublic(voMethod.getModifiers()) && (voMethod.getParameterTypes().length == 0)
                && !(voMethod.getReturnType().isAssignableFrom(Void.class))) {
            //Checking that it's a getter method, and it has a corresponding
            // setter method.
            if (voMethod.getName().startsWith("get") && !"getClass".equals(voMethod.getName())) {
                //Adding the field...
                result.add(voMethod.getName().substring(3, 4).toLowerCase() + voMethod.getName().substring(4));
            } else if (voMethod.getName().startsWith("is") && (Boolean.class.equals(voMethod.getReturnType())
                    || boolean.class.equals(voMethod.getReturnType()))) {
                //Adding the field...
                result.add(voMethod.getName().substring(2, 3).toLowerCase() + voMethod.getName().substring(3));

            }
        }
    }

    return result;
}

From source file:com.jaspersoft.jasperserver.util.QueryUtil.java

/**
 * Execute DataBaseMetaData methods using reflection
 * @param dmd/*from  w w  w .  ja  v  a  2  s.  c o  m*/
 * @param methodName
 * @param parameters
 * @return
 * @throws ClassNotFoundException
 */
public static Method findMethod(DatabaseMetaData dmd, String methodName, Object[] parameters)
        throws ClassNotFoundException {
    long startTime = System.currentTimeMillis();
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("Enter findMethod .. Start Time" + System.currentTimeMillis());
        }
        Class cl = Class.forName("java.sql.DatabaseMetaData");
        Method[] methods = cl.getDeclaredMethods();
        // Trying to avoid collision of methods with varying parameters and avoid having to do parameter class types

        int paramCount = 0;
        if (null != parameters) {
            paramCount = parameters.length;
        }

        for (Method m : methods) {
            if (m.getName().equals(methodName)) {
                if (Modifier.isPublic(m.getModifiers()) && m.getParameterTypes().length == paramCount) {
                    return m;
                }
            }
        } //for
        return null;
    } finally {
        if (logger.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            logger.debug("Exit findMethod .. Total Time Spent: " + elapsedTime);
        }
    }

}