Example usage for java.lang.reflect Modifier isPrivate

List of usage examples for java.lang.reflect Modifier isPrivate

Introduction

In this page you can find the example usage for java.lang.reflect Modifier isPrivate.

Prototype

public static boolean isPrivate(int mod) 

Source Link

Document

Return true if the integer argument includes the private modifier, false otherwise.

Usage

From source file:com.yahoo.egads.data.JsonEncoder.java

public static void fromJson(Object object, JSONObject json_obj) throws Exception {
    // for each json key-value, that has a corresponding variable in object ...
    for (Iterator k = json_obj.keys(); k.hasNext();) {
        String key = (String) k.next();
        Object value = json_obj.get(key);

        // try to access object variable
        Field field = null;//ww w .jav  a  2 s. c o  m
        try {
            field = object.getClass().getField(key);
        } catch (Exception e) {
            continue;
        }
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }
        Object member = field.get(object);

        if (json_obj.isNull(key)) {
            field.set(object, null);
            continue;
            // if variable is container... recurse
        } else if (member instanceof JsonAble) {
            ((JsonAble) member).fromJson((JSONObject) value);
            // if variable is an array... recurse on sub-objects
        } else if (member instanceof ArrayList) {
            // Depends on existance of ArrayList<T> template parameter, and T constructor with no arguments.
            // May be better to use custom fromJson() in member class.
            ArrayList memberArray = (ArrayList) member;
            JSONArray jsonArray = (JSONArray) value;

            // find array element constructor
            ParameterizedType arrayType = null;
            if (field.getGenericType() instanceof ParameterizedType) {
                arrayType = (ParameterizedType) field.getGenericType();
            }
            for (Class c = member.getClass(); arrayType == null && c != null; c = c.getSuperclass()) {
                if (c.getGenericSuperclass() instanceof ParameterizedType) {
                    arrayType = (ParameterizedType) c.getGenericSuperclass();
                }
            }
            if (arrayType == null) {
                throw new Exception("could not find ArrayList element type for field 'key'");
            }
            Class elementClass = (Class) (arrayType.getActualTypeArguments()[0]);
            Constructor elementConstructor = elementClass.getConstructor();

            // for each element in JSON array ... append element to member array, recursively decode element
            for (int i = 0; i < jsonArray.length(); ++i) {
                Object element = elementConstructor.newInstance();
                fromJson(element, jsonArray.getJSONObject(i));
                memberArray.add(element);
            }
            // if variable is simple value... set
        } else if (field.getType() == float.class) {
            field.set(object, (float) json_obj.getDouble(key));
        } else {
            field.set(object, value);
        }
    }
}

From source file:org.sonar.java.se.NullableAnnotationUtilsTest.java

@Test
public void private_constructor() throws Exception {
    assertThat(Modifier.isFinal(NullableAnnotationUtils.class.getModifiers())).isTrue();
    Constructor<NullableAnnotationUtils> constructor = NullableAnnotationUtils.class.getDeclaredConstructor();
    assertThat(Modifier.isPrivate(constructor.getModifiers())).isTrue();
    assertThat(constructor.isAccessible()).isFalse();
    constructor.setAccessible(true);/*  ww  w.  ja v  a2 s .  co m*/
    constructor.newInstance();
}

From source file:org.nuxeo.client.internals.spi.NuxeoClientException.java

public String getRemoteStackTrace() {
    Field[] fields = this.getClass().getDeclaredFields();
    StringBuilder result = new StringBuilder();
    for (Field field : fields) {
        try {//from  w w w . ja  v a2  s.  c om
            if (Modifier.isPrivate(field.getModifiers()) || field.get(this) == null) {
                continue;
            }
            result.append("  ");
            result.append(field.getName());
            result.append(": ");
            result.append(field.get(this));
        } catch (IllegalAccessException ex) {
            System.out.println(ex);
        }
        result.append(System.lineSeparator());
    }
    return result.toString();
}

From source file:com.qmetry.qaf.automation.step.JavaStepFinder.java

public static Map<String, TestStep> getAllJavaSteps() {
    Map<String, TestStep> stepMapping = new HashMap<String, TestStep>();
    Set<Method> steps = new LinkedHashSet<Method>();

    List<String> pkgs = new ArrayList<String>();
    pkgs.add(STEPS_PACKAGE);/*from w  ww. j a v a2s. co m*/

    if (getBundle().containsKey(STEP_PROVIDER_PKG.key)) {
        pkgs.addAll(Arrays.asList(getBundle().getStringArray(STEP_PROVIDER_PKG.key)));
    }
    for (String pkg : pkgs) {
        logger.info("pkg: " + pkg);
        try {
            List<Class<?>> classes = CLASS_FINDER.getClasses(pkg);
            steps.addAll(getAllMethodsWithAnnotation(classes, QAFTestStep.class));
        } catch (Exception e) {
            System.err.println("Unable to load steps for package: " + pkg);
        }
    }

    for (Method step : steps) {
        if (!Modifier.isPrivate(step.getModifiers())) {
            // exclude private methods.
            // Case: step provided using QAFTestStepProvider at class level
            add(stepMapping, new JavaStep(step));
        }
    }

    return stepMapping;

}

From source file:MyJavaP.java

/**
 * Format the fields and methods of one class, given its name.
 *//*from  w w w  . j  a  v a  2 s  .  com*/
protected void doClass(String className) {

    try {
        Class c = Class.forName(className);
        System.out.println(Modifier.toString(c.getModifiers()) + ' ' + c + " {");

        int mods;
        Field fields[] = c.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            if (!Modifier.isPrivate(fields[i].getModifiers())
                    && !Modifier.isProtected(fields[i].getModifiers()))
                System.out.println("\t" + fields[i]);
        }
        Constructor[] constructors = c.getConstructors();
        for (int j = 0; j < constructors.length; j++) {
            Constructor constructor = constructors[j];
            System.out.println("\t" + constructor);

        }
        Method methods[] = c.getDeclaredMethods();
        for (int i = 0; i < methods.length; i++) {
            if (!Modifier.isPrivate(methods[i].getModifiers())
                    && !Modifier.isProtected(methods[i].getModifiers()))
                System.out.println("\t" + methods[i]);
        }
        System.out.println("}");
    } catch (ClassNotFoundException e) {
        System.err.println("Error: Class " + className + " not found!");
    } catch (Exception e) {
        System.err.println(e);
    }
}

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

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

    if (c.isSynthetic()) {
        return false;
    }/*from   w  w w  . j a va 2  s .  c om*/

    // 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:com.feilong.commons.core.lang.reflect.FieldUtil.java

/**
 *  (?),key fieldNamevalue ./*from  w  ww. j a v a 2s . c o  m*/
 *
 * @param obj
 *            the obj
 * @param excludeFieldNames
 *            ?field names,?nullOrEmpty ?
 * @return the field value map
 * @throws ReflectException
 *             the reflect exception
 */
public static Map<String, Object> getFieldValueMap(Object obj, String[] excludeFieldNames)
        throws ReflectException {

    // (?,)
    Field[] fields = getDeclaredFields(obj);

    Map<String, Object> map = new TreeMap<String, Object>();
    if (Validator.isNotNullOrEmpty(fields)) {
        for (Field field : fields) {
            String fieldName = field.getName();

            if (Validator.isNotNullOrEmpty(excludeFieldNames)
                    && ArrayUtil.isContain(excludeFieldNames, fieldName)) {
                continue;
            }

            int modifiers = field.getModifiers();
            // ??? log
            boolean isPrivateAndStatic = Modifier.isPrivate(modifiers) && Modifier.isStatic(modifiers);
            log.debug("field name:[{}],modifiers:[{}],isPrivateAndStatic:[{}]", fieldName, modifiers,
                    isPrivateAndStatic);

            if (!isPrivateAndStatic) {
                //TODO see org.apache.commons.lang3.reflect.MemberUtils.setAccessibleWorkaround(AccessibleObject)
                field.setAccessible(true);
                try {
                    map.put(fieldName, field.get(obj));
                } catch (Exception e) {
                    log.error(e.getClass().getName(), e);
                    throw new ReflectException(e);
                }
            }
        }
    }
    return map;
}

From source file:com.judoscript.jamaica.parser.JamaicaDumpVisitor.java

public Object visit(ASTDefaultCtor node, Object data) throws Exception {
    out.print("\n  %default_constructor");
    int flags = node.getAccessFlags();
    if (Modifier.isPublic(flags))
        out.print(" <public>");
    else if (Modifier.isProtected(flags))
        out.print(" <protected>");
    else if (Modifier.isPrivate(flags))
        out.print(" <private>");
    out.println();/*from w  w  w. j av a2  s . c  o m*/
    return null;
}

From source file:org.compass.core.util.reflection.ReflectionFactory.java

private static boolean canGenerateAsm(Member member) {
    // we can only generate for members that are not private (so we can set them)
    // and that the class is public and not static (i.e. not intenral class within another class)
    return !Modifier.isPrivate(member.getModifiers());
}

From source file:net.duckling.falcon.api.orm.DAOUtils.java

/**
 * ??//  ww  w. j ava2s.com
 * 
 * @param objClass
 *            ?.class
 * */
public DAOUtils(Class<?> objClass) {
    this.objClass = objClass;
    Field[] allFields = objClass.getDeclaredFields();
    List<Field> privateFields = new ArrayList<Field>();
    for (int i = 0; i < allFields.length; i++) {
        if (!Modifier.isStatic(allFields[i].getModifiers()) && Modifier.isPrivate(allFields[i].getModifiers())
                && allFields[i].getAnnotation(TempField.class) == null) {
            privateFields.add(allFields[i]);
        }
    }
    this.fields = new Field[privateFields.size()];
    int index = 0;
    for (Field field : privateFields) {
        this.fields[index++] = field;
    }
}