Example usage for java.lang.reflect Field getModifiers

List of usage examples for java.lang.reflect Field getModifiers

Introduction

In this page you can find the example usage for java.lang.reflect Field getModifiers.

Prototype

public int getModifiers() 

Source Link

Document

Returns the Java language modifiers for the field represented by this Field object, as an integer.

Usage

From source file:ObjectAnalyzerTest.java

/**
 * Converts an object to a string representation that lists all fields.
 * //from  w  ww . jav a2  s. com
 * @param obj
 *          an object
 * @return a string with the object's class name and all field names and
 *         values
 */
public String toString(Object obj) {
    if (obj == null)
        return "null";
    if (visited.contains(obj))
        return "...";
    visited.add(obj);
    Class cl = obj.getClass();
    if (cl == String.class)
        return (String) obj;
    if (cl.isArray()) {
        String r = cl.getComponentType() + "[]{";
        for (int i = 0; i < Array.getLength(obj); i++) {
            if (i > 0)
                r += ",";
            Object val = Array.get(obj, i);
            if (cl.getComponentType().isPrimitive())
                r += val;
            else
                r += toString(val);
        }
        return r + "}";
    }

    String r = cl.getName();
    // inspect the fields of this class and all superclasses
    do {
        r += "[";
        Field[] fields = cl.getDeclaredFields();
        AccessibleObject.setAccessible(fields, true);
        // get the names and values of all fields
        for (Field f : fields) {
            if (!Modifier.isStatic(f.getModifiers())) {
                if (!r.endsWith("["))
                    r += ",";
                r += f.getName() + "=";
                try {
                    Class t = f.getType();
                    Object val = f.get(obj);
                    if (t.isPrimitive())
                        r += val;
                    else
                        r += toString(val);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        r += "]";
        cl = cl.getSuperclass();
    } while (cl != null);

    return r;
}

From source file:HashCodeAssist.java

/**
 * <p>// w w  w . j ava 2s  .  c om
 * Appends the fields and values defined by the given object of the given
 * <code>Class</code>.
 * </p>
 * 
 * @param object
 *            the object to append details of
 * @param clazz
 *            the class to append details of
 * @param builder
 *            the builder to append to
 * @param useTransients
 *            whether to use transient fields
 * @param excludeFields
 *            Collection of String field names to exclude from use in
 *            calculation of hash code
 */
private static void reflectionAppend(Object object, Class<?> clazz, HashCodeAssist builder,
        boolean useTransients, String... excludeFields) {
    if (isRegistered(object)) {
        return;
    }
    try {
        register(object);
        Field[] fields = clazz.getDeclaredFields();
        List<String> excludedFieldList = excludeFields != null ? Arrays.asList(excludeFields)
                : Collections.EMPTY_LIST;
        AccessibleObject.setAccessible(fields, true);
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            if (!excludedFieldList.contains(field.getName()) && (field.getName().indexOf('$') == -1)
                    && (useTransients || !Modifier.isTransient(field.getModifiers()))
                    && (!Modifier.isStatic(field.getModifiers()))) {
                try {
                    Object fieldValue = field.get(object);
                    builder.append(fieldValue);
                } catch (IllegalAccessException e) {
                    // this can't happen. Would get a Security exception
                    // instead
                    // throw a runtime exception in case the impossible
                    // happens.
                    throw new InternalError("Unexpected IllegalAccessException");
                }
            }
        }
    } finally {
        unregister(object);
    }
}

From source file:org.openlmis.fulfillment.ExposedMessageSourceIntegrationTest.java

private Set<String> getConstantValues(Class clazz) throws IllegalAccessException {
    Set<String> set = new HashSet<>();

    for (Field field : clazz.getDeclaredFields()) {
        int modifiers = field.getModifiers();

        if (isPublic(modifiers) && isStatic(modifiers) && isFinal(modifiers)) {
            set.add(String.valueOf(field.get(null)));
        }//from   www  .  j  ava2  s. c  o m
    }

    return set;
}

From source file:at.ac.tuwien.infosys.jcloudscale.utility.ReflectionUtil.java

public static void checkLegalCloudIdDef(Object obj) {

    for (Field f : obj.getClass().getDeclaredFields()) {
        if (f.getAnnotation(CloudObjectId.class) != null) {

            if (!f.getType().equals(UUID.class) && !f.getType().equals(String.class)
                    && !f.getType().equals(Object.class))
                throw new IllegalDefinitionException("Illegal field type " + f.getType().getName()
                        + " annotated with "
                        + "@CloudObjectId. You may only annotate java.lang.Object, java.lang.String and java.util.UUID");

            if (Modifier.isStatic(f.getModifiers()))
                throw new IllegalDefinitionException("Illegal field " + f.getName()
                        + " annotated with @CloudObjectId. " + "Field has to be non-static.");

        }//from w  w  w .  j  a  v a2 s.  co  m
    }

}

From source file:net.minecraftforge.common.util.EnumHelper.java

@SuppressWarnings({ "unchecked", "serial" })
@Nullable//from w ww.  j  av  a 2s.  c  om
private static <T extends Enum<?>> T addEnum(boolean test, final Class<T> enumType, @Nullable String enumName,
        final Class<?>[] paramTypes, @Nullable Object[] paramValues) {
    if (!isSetup) {
        setup();
    }

    Field valuesField = null;
    Field[] fields = enumType.getDeclaredFields();

    for (Field field : fields) {
        String name = field.getName();
        if (name.equals("$VALUES") || name.equals("ENUM$VALUES")) //Added 'ENUM$VALUES' because Eclipse's internal compiler doesn't follow standards
        {
            valuesField = field;
            break;
        }
    }

    int flags = (FMLForgePlugin.RUNTIME_DEOBF ? Modifier.PUBLIC : Modifier.PRIVATE) | Modifier.STATIC
            | Modifier.FINAL | 0x1000 /*SYNTHETIC*/;
    if (valuesField == null) {
        String valueType = String.format("[L%s;", enumType.getName().replace('.', '/'));

        for (Field field : fields) {
            if ((field.getModifiers() & flags) == flags
                    && field.getType().getName().replace('.', '/').equals(valueType)) //Apparently some JVMs return .'s and some don't..
            {
                valuesField = field;
                break;
            }
        }
    }

    if (valuesField == null) {
        final List<String> lines = Lists.newArrayList();
        lines.add(String.format("Could not find $VALUES field for enum: %s", enumType.getName()));
        lines.add(String.format("Runtime Deobf: %s", FMLForgePlugin.RUNTIME_DEOBF));
        lines.add(String.format("Flags: %s",
                String.format("%16s", Integer.toBinaryString(flags)).replace(' ', '0')));
        lines.add("Fields:");
        for (Field field : fields) {
            String mods = String.format("%16s", Integer.toBinaryString(field.getModifiers())).replace(' ', '0');
            lines.add(String.format("       %s %s: %s", mods, field.getName(), field.getType().getName()));
        }

        for (String line : lines)
            FMLLog.log.fatal(line);

        if (test) {
            throw new EnhancedRuntimeException("Could not find $VALUES field for enum: " + enumType.getName()) {
                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    for (String line : lines)
                        stream.println(line);
                }
            };
        }
        return null;
    }

    if (test) {
        Object ctr = null;
        Exception ex = null;
        try {
            ctr = getConstructorAccessor(enumType, paramTypes);
        } catch (Exception e) {
            ex = e;
        }
        if (ctr == null || ex != null) {
            throw new EnhancedRuntimeException(
                    String.format("Could not find constructor for Enum %s", enumType.getName()), ex) {
                private String toString(Class<?>[] cls) {
                    StringBuilder b = new StringBuilder();
                    for (int x = 0; x < cls.length; x++) {
                        b.append(cls[x].getName());
                        if (x != cls.length - 1)
                            b.append(", ");
                    }
                    return b.toString();
                }

                @Override
                protected void printStackTrace(WrappedPrintStream stream) {
                    stream.println("Target Arguments:");
                    stream.println("    java.lang.String, int, " + toString(paramTypes));
                    stream.println("Found Constructors:");
                    for (Constructor<?> ctr : enumType.getDeclaredConstructors()) {
                        stream.println("    " + toString(ctr.getParameterTypes()));
                    }
                }
            };
        }
        return null;
    }

    valuesField.setAccessible(true);

    try {
        T[] previousValues = (T[]) valuesField.get(enumType);
        T newValue = makeEnum(enumType, enumName, previousValues.length, paramTypes, paramValues);
        setFailsafeFieldValue(valuesField, null, ArrayUtils.add(previousValues, newValue));
        cleanEnumCache(enumType);

        return newValue;
    } catch (Exception e) {
        FMLLog.log.error("Error adding enum with EnumHelper.", e);
        throw new RuntimeException(e);
    }
}

From source file:me.xiaopan.android.gohttp.requestobject.RequestParser.java

/**
 * ??//www . j  av  a 2  s .c  om
 * @param context 
 * @param requestClass class??class??????
 * @param requestParams ??null????????
 * @return ?
 */
@SuppressWarnings("unchecked")
public static RequestParams parseRequestParams(Context context, Class<? extends Request> requestClass,
        RequestParams requestParams) {
    if (requestParams == null) {
        requestParams = new RequestParams();
    }

    String requestParamName;
    String requestParamValue;
    Object requestParamValueObject = null;
    for (Field field : getFields(requestClass, true, true, true)) {
        // ???????
        if (!field.isAnnotationPresent(Param.class) || !Modifier.isStatic(field.getModifiers())) {
            continue;
        }

        // ????
        requestParamName = parseParamAnnotation(context, field);
        if (requestParamName == null) {
            requestParamName = field.getName();
        }

        // ?ValueValue?
        if (field.isAnnotationPresent(Value.class)) {
            String value = parseValueAnnotation(context, field);
            if (value != null) {
                requestParams.put(requestParamName, value);
                continue;
            }
        }

        try {
            field.setAccessible(true);
            requestParamValueObject = field.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        // ?null?
        if (requestParamValueObject == null) {
            continue;
        }

        // ?Map???
        if (Map.class.isAssignableFrom(field.getType())) {
            for (java.util.Map.Entry<Object, Object> entry : ((Map<Object, Object>) requestParamValueObject)
                    .entrySet()) {
                if (entry.getKey() != null && entry.getValue() != null) {
                    String key = entry.getKey().toString();
                    String value = entry.getValue().toString();
                    if (key != null && !"".equals(key) && value != null && !"".equals(value)) {
                        requestParams.put(key, value);
                    }
                }
            }
            continue;
        }

        // ?File?
        if (File.class.isAssignableFrom(field.getType())) {
            try {
                requestParams.put(requestParamName, (File) requestParamValueObject);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            continue;
        }

        // ?ArrayListArrayList?
        if (ArrayList.class.isAssignableFrom(field.getType())) {
            requestParams.put(requestParamName, (ArrayList<String>) requestParamValueObject);
            continue;
        }

        // ?boolean
        if (Boolean.class.isAssignableFrom(field.getType())) {
            if ((Boolean) requestParamValueObject) {
                requestParamValue = parseTrueAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_TRUE;
                }
            } else {
                requestParamValue = parseFalseAnnotation(context, field);
                if (requestParamValue == null) {
                    requestParamValue = DEFAULT_VALUE_FALSE;
                }
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ?
        if (Enum.class.isAssignableFrom(field.getType())) {
            Enum<?> enumObject = (Enum<?>) requestParamValueObject;
            requestParamValue = parseValueAnnotationFromEnum(context, enumObject);
            if (requestParamValue == null) {
                requestParamValue = enumObject.name();
            }
            requestParams.put(requestParamName, requestParamValue);
            continue;
        }

        // ???
        requestParamValue = requestParamValueObject.toString();
        if (requestParamValue != null && !"".equals(requestParamValue)) {
            requestParams.put(requestParamName, requestParamValue);
        }
    }

    return requestParams;
}

From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.EntitlementItemAttributeDataInitializer.java

@Override
public Collection<EntitlementItemAttribute> create() {
    ArrayList<EntitlementItemAttribute> attributes = new ArrayList<>();
    // Software License
    EntitlementType sl = entitlementTypeDataInitializer.getByName("SL");
    // Software License - Item Attributes
    Field[] itemFields = FieldUtils.getAllFields(SoftwareLicenseEntitlementItem.class);
    sl.setItemAttributes(new ArrayList<>(itemFields.length));
    for (Field itemField : itemFields) {
        if (!Modifier.isStatic(itemField.getModifiers()) &&
        // Exclusion from JPA annotations
                CollectionUtils.isEmpty(CollectionUtils.intersection(
                        // Annotations
                        Arrays.asList(itemField.getAnnotations()).stream()
                                .map(annotation -> annotation.annotationType()).collect(Collectors.toList()),
                        // Exclusions
                        EXCLUSION_PROPERTY_ATTRIBUTES)))
            sl.getItemAttributes()//from  w  w w  .  j a v  a2  s  .  c o  m
                    .add(generateEntitlementAttributes(itemField, new EntitlementItemAttribute()));
    }
    for (EntitlementItemAttribute itemAttribute : sl.getItemAttributes()) {
        itemAttribute.setEntitlementType(sl);
        attributes.add(itemAttribute);
    }

    return attributes;
}

From source file:org.opentele.server.core.util.CustomGroovyBeanJSONMarshaller.java

public void marshalObject(Object o, JSON json) throws ConverterException {
    JSONWriter writer = json.getWriter();
    try {//from   w  w  w . j  av  a 2s .c  om
        writer.object();
        for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(o.getClass())) {
            String name = property.getName();
            Method readMethod = property.getReadMethod();
            if (readMethod != null && !(name.equals("metaClass")) && !(name.equals("class"))) {
                Object value = readMethod.invoke(o, (Object[]) null);
                writer.key(name);
                json.convertAnother(value);
            }
        }
        for (Field field : o.getClass().getDeclaredFields()) {
            int modifiers = field.getModifiers();
            if (Modifier.isPublic(modifiers)
                    && !(Modifier.isStatic(modifiers) || Modifier.isTransient(modifiers))) {
                writer.key(field.getName());
                json.convertAnother(field.get(o));
            }
        }
        writer.endObject();
    } catch (ConverterException ce) {
        throw ce;
    } catch (Exception e) {
        throw new ConverterException("Error converting Bean with class " + o.getClass().getName(), e);
    }
}

From source file:com.sap.csc.poc.ems.persistence.initial.entitlement.EntitlementHeaderAttributeDataInitializer.java

@Override
public Collection<EntitlementHeaderAttribute> create() {
    ArrayList<EntitlementHeaderAttribute> attributes = new ArrayList<>();
    // Software License
    EntitlementType sl = entitlementTypeDataInitializer.getByName("SL");
    // Software License - Header Attributes
    Field[] headerFields = FieldUtils.getAllFields(SoftwareLicenseEntitlementHeader.class);
    sl.setHeaderAttributes(new ArrayList<>(headerFields.length));
    for (Field headerField : headerFields) {
        if (!Modifier.isStatic(headerField.getModifiers()) &&
        // Exclusion from JPA annotations
                CollectionUtils.isEmpty(CollectionUtils.intersection(
                        // Annotations
                        Arrays.asList(headerField.getAnnotations()).stream()
                                .map(annotation -> annotation.annotationType()).collect(Collectors.toList()),
                        // Exclusions
                        EXCLUSION_PROPERTY_ATTRIBUTES)))
            sl.getHeaderAttributes()/*from   ww  w  . j a  va  2s.  co m*/
                    .add(generateEntitlementAttributes(headerField, new EntitlementHeaderAttribute()));
    }
    for (EntitlementHeaderAttribute headerAttribute : sl.getHeaderAttributes()) {
        headerAttribute.setEntitlementType(sl);
        attributes.add(headerAttribute);
    }

    return attributes;
}

From source file:de.bstreit.java.oscr.initialdata.AbstractDataContainer.java

/**
 * //from  w w w.j a v  a  2 s.c  o m
 * @param field
 * @return true, if the field is a constant (public static final) and of the
 *         expected type provided by {@link #getType()}
 */
private boolean isConstantAndOfType(Field field) {
    final int modifiers = field.getModifiers();

    final boolean isConstant = Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers)
            && Modifier.isPublic(modifiers);

    final boolean correctType = field.getType().equals(getType());

    return isConstant && correctType;
}