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.glaf.core.util.ReflectUtils.java

public static void setFieldValue(Object target, String fieldName, Object fieldValue) {
    try {/*from   w w  w.  ja  va 2 s  .c  om*/
        Field field = ReflectionUtils.findField(target.getClass(), fieldName);
        if (field != null && !Modifier.isPublic(field.getModifiers())) {
            field.setAccessible(true);
        }
        ReflectionUtils.setField(field, target, fieldValue);
    } catch (Exception ex) {
        try {
            BeanUtils.setProperty(target, fieldName, fieldValue);
        } catch (Exception e) {
        }
    }
}

From source file:objenome.util.ClassUtils.java

/**
 * <p>Returns the desired Method much like {@code Class.getMethod}, however
 * it ensures that the returned Method is from a public class or interface and not
 * from an anonymous inner class. This means that the Method is invokable and
 * doesn't fall foul of Java bug/*from   w w  w. j av a 2s  . co m*/
 * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4071957">4071957</a>).</p>
 *
 *  <pre>
 *  <code>Set set = Collections.unmodifiableSet(...);
 *  Method method = ClassUtils.getPublicMethod(set.getClass(), "isEmpty",  new Class[0]);
 *  Object result = method.invoke(set, new Object[]);</code>
 *  </pre>
 *
 * @param cls  the class to check, not null
 * @param methodName  the name of the method
 * @param parameterTypes  the list of parameters
 * @return the method
 * @throws NullPointerException if the class is null
 * @throws SecurityException if a security violation occurred
 * @throws NoSuchMethodException if the method is not found in the given class
 *  or if the method doesn't conform with the requirements
 */
public static Method getPublicMethod(Class<?> cls, String methodName, Class<?>... parameterTypes)
        throws SecurityException, NoSuchMethodException {

    Method declaredMethod = cls.getMethod(methodName, parameterTypes);
    if (Modifier.isPublic(declaredMethod.getDeclaringClass().getModifiers())) {
        return declaredMethod;
    }

    List<Class<?>> candidateClasses = new ArrayList<>(getAllInterfaces(cls));
    candidateClasses.addAll(getAllSuperclasses(cls));

    for (Class<?> candidateClass : candidateClasses) {
        if (!Modifier.isPublic(candidateClass.getModifiers())) {
            continue;
        }
        Method candidateMethod;
        try {
            candidateMethod = candidateClass.getMethod(methodName, parameterTypes);
        } catch (NoSuchMethodException ex) {
            continue;
        }
        if (Modifier.isPublic(candidateMethod.getDeclaringClass().getModifiers())) {
            return candidateMethod;
        }
    }

    throw new NoSuchMethodException(
            "Can't find a public method for " + methodName + ' ' + ArrayUtils.toString(parameterTypes));
}

From source file:com.ng.mats.psa.mt.paga.data.JSONObject.java

private void populateMap(Object bean) {
    Class<?> klass = bean.getClass();

    // If klass is a System class then set includeSuperClass to false.

    boolean includeSuperClass = klass.getClassLoader() != null;

    Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i += 1) {
        try {// ww  w  .  j a v a  2  s  . c o  m
            Method method = methods[i];
            if (Modifier.isPublic(method.getModifiers())) {
                String name = method.getName();
                String key = "";
                if (name.startsWith("get")) {
                    if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
                        key = "";
                    } else {
                        key = name.substring(3);
                    }
                } else if (name.startsWith("is")) {
                    key = name.substring(2);
                }
                if (key.length() > 0 && Character.isUpperCase(key.charAt(0))
                        && method.getParameterTypes().length == 0) {
                    if (key.length() == 1) {
                        key = key.toLowerCase();
                    } else if (!Character.isUpperCase(key.charAt(1))) {
                        key = key.substring(0, 1).toLowerCase() + key.substring(1);
                    }

                    Object result = method.invoke(bean, (Object[]) null);
                    if (result != null) {
                        this.map.put(key, wrap(result));
                    }
                }
            }
        } catch (Exception ignore) {
        }
    }
}

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

public static boolean hasNoArgConstructor(Constructor[] constructors) {
    for (Constructor c : constructors) {
        if ((Modifier.isProtected(c.getModifiers()) || Modifier.isPublic(c.getModifiers()))
                && c.getParameterTypes().length == 0) {
            return true;
        }/*from ww  w  .ja  va 2  s.com*/
    }
    return false;
}

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

private static boolean addGetterMethod(Field f, Class clss, List<Class> classes) {
    if (!Modifier.isPublic(f.getModifiers())) {
        return false;
    }//from w w  w.ja  v a 2s. co m
    if (!f.getType().isPrimitive() && !String.class.equals(f.getType()) && !classes.contains(f.getType())) {
        return false;
    }
    Method ma[] = clss.getMethods();
    for (int i = 0; i < ma.length; i++) {
        Method method = ma[i];
        if (method.getName().equalsIgnoreCase(f.getName())) {
            return false;
        }
        if (method.getName().equalsIgnoreCase("get" + f.getName())) {
            return false;
        }
        if (method.getName().equalsIgnoreCase("set" + f.getName())) {
            return false;
        }
    }
    return true;
}

From source file:org.apache.axis.wsdl.fromJava.Types.java

/**
 * Write Enumeration Complex Type/*from w ww . j a v  a 2s .c o m*/
 * (Only supports enumeration classes of string types)
 *
 * @param qName QName of type.
 * @param cls   class of type
 * @return
 * @throws NoSuchMethodException
 * @throws IllegalAccessException
 * @throws AxisFault
 */
public Element writeEnumType(QName qName, Class cls)
        throws NoSuchMethodException, IllegalAccessException, AxisFault {

    if (!isEnumClass(cls)) {
        return null;
    }

    // Get the base type of the enum class
    java.lang.reflect.Method m = cls.getMethod("getValue", null);
    Class base = m.getReturnType();

    // Create simpleType, restriction elements
    Element simpleType = docHolder.createElement("simpleType");

    simpleType.setAttribute("name", qName.getLocalPart());

    Element restriction = docHolder.createElement("restriction");

    simpleType.appendChild(restriction);

    String baseType = writeType(base, null);

    restriction.setAttribute("base", baseType);

    // Create an enumeration using the field values
    Field[] fields = cls.getDeclaredFields();

    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        int mod = field.getModifiers();

        // Inspect each public static final field of the same type
        // as the base
        if (Modifier.isPublic(mod) && Modifier.isStatic(mod) && Modifier.isFinal(mod)
                && (field.getType() == base)) {

            // Create an enumeration using the value specified
            Element enumeration = docHolder.createElement("enumeration");

            enumeration.setAttribute("value", field.get(null).toString());
            restriction.appendChild(enumeration);
        }
    }

    return simpleType;
}

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

private static boolean addSetterMethod(Field f, Class clss, List<Class> classes) {
    if (!Modifier.isPublic(f.getModifiers())) {
        return false;
    }//w  w w.  ja  v a 2 s  . co m
    if (!f.getType().isPrimitive() && !String.class.equals(f.getType()) && !classes.contains(f.getType())) {
        return false;
    }
    if (Modifier.isFinal(f.getModifiers())) {
        return false;
    }
    Method ma[] = clss.getMethods();
    for (int i = 0; i < ma.length; i++) {
        Method method = ma[i];
        if (method.getName().equalsIgnoreCase(f.getName())) {
            return false;
        }
        if (method.getName().equalsIgnoreCase("get" + f.getName())) {
            return false;
        }
        if (method.getName().equalsIgnoreCase("set" + f.getName())) {
            return false;
        }
    }
    return true;
}

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

/**
 * Look for methods matching this name, and for each one, create an
 * OperationDesc (if it's not already in our list).
 *
 * TODO: Make this more efficient/* ww w  .  ja va  2s  .  com*/
 */
private void createOperationsForName(Class implClass, String methodName) {
    // If we're a Skeleton deployment, skip the statics.
    if (isSkeletonClass) {
        if (methodName.equals("getOperationDescByName") || methodName.equals("getOperationDescs"))
            return;
    }

    Method[] methods = getMethods(implClass);

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

    Class superClass = implClass.getSuperclass();
    if (superClass != null && !superClass.getName().startsWith("java.")
            && !superClass.getName().startsWith("javax.")
            && (stopClasses == null || !stopClasses.contains(superClass.getName()))) {
        createOperationsForName(superClass, methodName);
    }
}

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

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

    if (c.isSynthetic()) {
        return false;
    }//from   w  w  w . j  a  v a2 s  .c  o m

    // 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() && !canUse(c.getDeclaringClass()))
        return false;

    if (!Properties.USE_DEPRECATED && c.getAnnotation(Deprecated.class) != null) {
        logger.debug("Skipping deprecated constructor {}", c.getName());
        return false;
    }

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

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

    // 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)) {
            makeAccessible(c);
            return true;
        }
    }

    return false;
}

From source file:com.google.ratel.util.RatelUtils.java

private static Object createDeepInstance(Class type, Set<Class> cyclicDetector) {
    cyclicDetector.add(type);//from  w  w  w . j  a  v a2  s. co m
    //System.out.println("Depth: " + callingDepth);

    try {
        Object obj = null;

        // Handle primitives
        if (defaultValues.containsKey(type)) {
            Object defaultValue = defaultValues.get(type);
            obj = defaultValue;

            // Handle Arrays
        } else if (type.isArray()) {
            Class arrayType = type.getComponentType();

            // Check cyclic dependency
            if (!cyclicDetector.contains(arrayType)) {

                Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                Object value = createDeepInstance(arrayType, localCyclicDetector);
                obj = Array.newInstance(arrayType, 1);
                Array.set(obj, 0, value);
            }

        } else {
            // Handle pojo
            obj = type.newInstance();

            List<Field> fullFieldList = getAllFields(type);

            for (Field field : fullFieldList) {
                Class fieldType = field.getType();

                // Check for cyclic dependency
                if (!cyclicDetector.contains(fieldType)) {
                    Set<Class> localCyclicDetector = new HashSet<Class>(cyclicDetector);
                    Object fieldObj = createDeepInstance(fieldType, localCyclicDetector);
                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(true);
                    }

                    field.set(obj, fieldObj);

                    if (!Modifier.isPublic(field.getModifiers())) {
                        field.setAccessible(false);
                    }
                }

            }
        }
        return obj;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}