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.getobjects.foundation.kvc.KVCWrapper.java

@SuppressWarnings("unchecked")
private static Method[] getPublicDeclaredMethods(Class _class) {
    Method methods[] = declaredMethodCache.get(_class);
    if (methods != null)
        return methods;

    final Class fclz = _class;

    methods = (Method[]) AccessController.doPrivileged(new PrivilegedAction() {
        public Object run() {
            return fclz.getMethods();
        }/*from w w  w  .  ja va 2 s .co  m*/
    });

    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        int j = method.getModifiers();
        if (!Modifier.isPublic(j))
            methods[i] = null;
    }

    declaredMethodCache.put(_class, methods);
    return methods;
}

From source file:org.codehaus.groovy.grails.commons.ClassPropertyFetcher.java

private void init() {
    FieldCallback fieldCallback = new ReflectionUtils.FieldCallback() {
        public void doWith(Field field) {
            if (field.isSynthetic()) {
                return;
            }//  w w w . j a v a  2  s.  c  o m
            final int modifiers = field.getModifiers();
            if (!Modifier.isPublic(modifiers)) {
                return;
            }

            final String name = field.getName();
            if (name.indexOf('$') == -1) {
                boolean staticField = Modifier.isStatic(modifiers);
                if (staticField) {
                    staticFetchers.put(name, new FieldReaderFetcher(field, staticField));
                } else {
                    instanceFetchers.put(name, new FieldReaderFetcher(field, staticField));
                }
            }
        }
    };

    MethodCallback methodCallback = new ReflectionUtils.MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            if (method.isSynthetic()) {
                return;
            }
            if (!Modifier.isPublic(method.getModifiers())) {
                return;
            }
            if (Modifier.isStatic(method.getModifiers()) && method.getReturnType() != Void.class) {
                if (method.getParameterTypes().length == 0) {
                    String name = method.getName();
                    if (name.indexOf('$') == -1) {
                        if (name.length() > 3 && name.startsWith("get")
                                && Character.isUpperCase(name.charAt(3))) {
                            name = name.substring(3);
                        } else if (name.length() > 2 && name.startsWith("is")
                                && Character.isUpperCase(name.charAt(2))
                                && (method.getReturnType() == Boolean.class
                                        || method.getReturnType() == boolean.class)) {
                            name = name.substring(2);
                        }
                        PropertyFetcher fetcher = new GetterPropertyFetcher(method, true);
                        staticFetchers.put(name, fetcher);
                        staticFetchers.put(StringUtils.uncapitalize(name), fetcher);
                    }
                }
            }
        }
    };

    List<Class<?>> allClasses = resolveAllClasses(clazz);
    for (Class<?> c : allClasses) {
        Field[] fields = c.getDeclaredFields();
        for (Field field : fields) {
            try {
                fieldCallback.doWith(field);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
            }
        }
        Method[] methods = c.getDeclaredMethods();
        for (Method method : methods) {
            try {
                methodCallback.doWith(method);
            } catch (IllegalAccessException ex) {
                throw new IllegalStateException(
                        "Shouldn't be illegal to access method '" + method.getName() + "': " + ex);
            }
        }
    }

    propertyDescriptors = BeanUtils.getPropertyDescriptors(clazz);
    for (PropertyDescriptor desc : propertyDescriptors) {
        Method readMethod = desc.getReadMethod();
        if (readMethod != null) {
            boolean staticReadMethod = Modifier.isStatic(readMethod.getModifiers());
            if (staticReadMethod) {
                staticFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            } else {
                instanceFetchers.put(desc.getName(), new GetterPropertyFetcher(readMethod, staticReadMethod));
            }
        }
    }
}

From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java

@SuppressWarnings({ "rawtypes", "unchecked" })
private static <T> void checkBeanValidity(Class<T> clazz, List<String> excludeFieldList,
        int recursiveCycleLimit) {
    PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz);
    boolean validBean = false;
    for (PropertyDescriptor pd : pds) {
        if (pd.getWriteMethod() != null && pd.getReadMethod() != null && //
                (excludeFieldList != null && !excludeFieldList.contains(pd.getName())
                        || excludeFieldList == null) //
        ) {// w w  w  .ja v  a 2 s .  c o  m
            validBean = true;
            // just set write ,read for user control
            if (!Modifier.isPublic(pd.getWriteMethod().getDeclaringClass().getModifiers())) {
                pd.getWriteMethod().setAccessible(true);
            }

            Class fieldClazz = pd.getPropertyType();
            if (!TypeUtil.isBaseType(fieldClazz)) {
                try {
                    // ????
                    if (recursiveCycleLimit == 0 && fieldClazz == clazz) {
                        throw new RuntimeException("recursive cycle limit is 0! field[" + pd.getName()
                                + "] may cause recursive, please add this field[" + pd.getName()
                                + "] to exclude list or set recursiveCycleLimit more than 0 .");
                    } else if (!fieldClazz.isAssignableFrom(clazz)) {
                        checkBeanValidity(fieldClazz, null, 999999999);
                    }
                } catch (Exception e) {
                    throw new RuntimeException("Unknown Class " + fieldClazz.getName() + " for field "
                            + pd.getName() + " ! please add this field[" + pd.getName() + "] to exclude list.",
                            e);
                }
            }
        }
    }
    if (!validBean) {
        throw new RuntimeException(
                "Invalid Bean Class[" + clazz.getName() + "], for it has not getter setter methods!");
    }
}

From source file:com.weibo.api.motan.config.AbstractConfig.java

/**
 * config ?Map//  w w  w .j a va 2  s.  c o m
 * 
 * @param parameters
 */
@SuppressWarnings("unchecked")
protected void appendConfigParams(Map<String, String> parameters, String prefix) {
    Method[] methods = this.getClass().getMethods();
    for (Method method : methods) {
        try {
            String name = method.getName();
            if (isConfigMethod(method)) {
                int idx = name.startsWith("get") ? 3 : 2;
                String prop = name.substring(idx, idx + 1).toLowerCase() + name.substring(idx + 1);
                String key = prop;
                ConfigDesc configDesc = method.getAnnotation(ConfigDesc.class);
                if (configDesc != null && !StringUtils.isBlank(configDesc.key())) {
                    key = configDesc.key();
                }

                Object value = method.invoke(this);
                if (value == null || StringUtils.isBlank(String.valueOf(value))) {
                    if (configDesc != null && configDesc.required()) {
                        throw new MotanFrameworkException(
                                String.format("%s.%s should not be null or empty",
                                        this.getClass().getSimpleName(), key),
                                MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
                    }
                    continue;
                }
                if (prefix != null && prefix.length() > 0) {
                    key = prefix + "." + key;
                }
                parameters.put(key, String.valueOf(value).trim());
            } else if ("getParameters".equals(name) && Modifier.isPublic(method.getModifiers())
                    && method.getParameterTypes().length == 0 && method.getReturnType() == Map.class) {
                Map<String, String> map = (Map<String, String>) method.invoke(this);
                if (map != null && map.size() > 0) {
                    String pre = prefix != null && prefix.length() > 0 ? prefix + "." : "";
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        parameters.put(pre + entry.getKey(), entry.getValue());
                    }
                }
            }
        } catch (Exception e) {
            throw new MotanFrameworkException(String.format("Error when append params for config: %s.%s",
                    this.getClass().getSimpleName(), method.getName()), e,
                    MotanErrorMsgConstant.FRAMEWORK_INIT_ERROR);
        }
    }
}

From source file:org.alex73.skarynka.scan.Book2.java

private void set(Object obj, String fieldName, String value, String debug) {
    try {// w ww .ja v a 2 s  .  com
        Field f = obj.getClass().getField(fieldName);
        if (!Modifier.isPublic(f.getModifiers()) || Modifier.isStatic(f.getModifiers())
                || Modifier.isTransient(f.getModifiers())) {
            errors.add("Field is not public for '" + debug + "'");
            return;
        }
        if (f.getType() == int.class) {
            f.setInt(obj, Integer.parseInt(value));
        } else if (f.getType() == boolean.class) {
            f.setBoolean(obj, Boolean.parseBoolean(value));
        } else if (f.getType() == String.class) {
            f.set(obj, value);
        } else if (Set.class.isAssignableFrom(f.getType())) {
            TreeSet<String> v = new TreeSet<>(Arrays.asList(value.split(";")));
            f.set(obj, v);
        } else {
            errors.add("Unknown field class for set '" + debug + "'");
            return;
        }
    } catch (NoSuchFieldException ex) {
        errors.add("Unknown field for set '" + debug + "'");
    } catch (IllegalAccessException ex) {
        errors.add("Wrong field for set '" + debug + "'");
    } catch (Exception ex) {
        errors.add("Error set value to field for '" + debug + "'");
    }
}

From source file:in.hatimi.nosh.support.CommandExecutor.java

private Method findMainMethod() {
    Method[] methods = cmdCls.getMethods();
    for (Method method : methods) {
        if (!method.getName().equals("execute")) {
            continue; //method name must be 'execute'
        }/* w  w w . ja  va 2  s  .co  m*/
        int mod = method.getModifiers();
        if (Modifier.isAbstract(mod)) {
            continue; //method cannot be abstract.
        }
        if (Modifier.isStatic(mod)) {
            continue; //method cannot be static.
        }
        if (Modifier.isSynchronized(mod)) {
            continue; //method cannot be synthetic.
        }
        if (!Modifier.isPublic(mod)) {
            continue; //method must be public.
        }
        if (method.getReturnType() != Void.TYPE) {
            continue; //method must not return a value.
        }
        Class<?>[] paramTypes = method.getParameterTypes();
        if (paramTypes.length > 1) {
            continue; //method can take at most one parameter.
        }
        if (paramTypes.length == 1 && !paramTypes[0].equals(String[].class)) {
            continue; //if single parameter, must be String[]
        }
        return method;
    }
    return null;
}

From source file:org.apache.flink.runtime.fs.hdfs.HadoopRecoverableFsDataOutputStream.java

private static void ensureTruncateInitialized() throws FlinkRuntimeException {
    if (truncateHandle == null) {
        Method truncateMethod;/*from  ww  w . j a v  a  2s  .  c  o m*/
        try {
            truncateMethod = FileSystem.class.getMethod("truncate", Path.class, long.class);
        } catch (NoSuchMethodException e) {
            throw new FlinkRuntimeException(
                    "Could not find a public truncate method on the Hadoop File System.");
        }

        if (!Modifier.isPublic(truncateMethod.getModifiers())) {
            throw new FlinkRuntimeException(
                    "Could not find a public truncate method on the Hadoop File System.");
        }

        truncateHandle = truncateMethod;
    }
}

From source file:it.unibas.spicy.persistence.object.operators.AnalyzeFields.java

private boolean findPublicMethodInClass(Class currentClass, String methodName) {
    Method[] methods = currentClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.getName().equals(methodName) && Modifier.isPublic(method.getModifiers())) {
            return true;
        }//from  ww  w .j a  v a  2 s.  c  o m
    }
    return false;
}

From source file:org.shept.util.BeanUtilsExtended.java

/**
 * Merge the property values of the given source bean into the given target bean.
 * <p>Note: Only not-null values are merged into the given target bean.
 * Note: The source and target classes do not have to match or even be derived
 * from each other, as long as the properties match. Any bean properties that the
 * source bean exposes but the target bean does not will silently be ignored.
 * @param source the source bean/*w w w.  j  a v a2s .com*/
 * @param target the target bean
 * @param editable the class (or interface) to restrict property setting to
 * @param ignoreProperties array of property names to ignore
 * @throws BeansException if the copying failed
 * @see BeanWrapper
 */
private static void mergeProperties(Object source, Object target, 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() + "]");
        }
        actualEditable = editable;
    }
    PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
    List<String> ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;

    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null
                && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {
            PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(source);
                    if (value != null) {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, value);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}

From source file:com.zero.service.impl.BaseServiceImpl.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private void copyProperties(Object source, Object target) throws BeansException {
    Assert.notNull(source, "Source must not be null");
    Assert.notNull(target, "Target must not be null");

    PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(target.getClass());
    for (PropertyDescriptor targetPd : targetPds) {
        if (targetPd.getWriteMethod() != null) {
            PropertyDescriptor sourcePd = BeanUtils.getPropertyDescriptor(source.getClass(),
                    targetPd.getName());
            if (sourcePd != null && sourcePd.getReadMethod() != null) {
                try {
                    Method readMethod = sourcePd.getReadMethod();
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }//  w  w w . j av a  2 s  . c  om
                    Object sourceValue = readMethod.invoke(source);
                    Object targetValue = readMethod.invoke(target);
                    if (sourceValue != null && targetValue != null && targetValue instanceof Collection) {
                        Collection collection = (Collection) targetValue;
                        collection.clear();
                        collection.addAll((Collection) sourceValue);
                    } else {
                        Method writeMethod = targetPd.getWriteMethod();
                        if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                            writeMethod.setAccessible(true);
                        }
                        writeMethod.invoke(target, sourceValue);
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException("Could not copy properties from source to target", ex);
                }
            }
        }
    }
}