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:fi.kela.kanta.util.GenericToString.java

/**
 * Geneerinen toString metodi, jolla saadaan yksinkertainen siisti key=value listaus annetun luokan attribuuteista.
 *
 * @param obj//from  w  w  w.  ja  v  a 2 s .  c om
 *            Objekti jonka tiedot halutaan tulostaa.
 * @return Listaus annetun objektin attribuuteista ja niiden arvoista.
 */
public String toString(Object obj) {

    StringBuilder sb = new StringBuilder();
    sb.append(obj.getClass().getSimpleName());
    sb.append(GenericToString.open_parameters);

    boolean fieldsAdded = false;
    for (Field field : GenericToString.getAllFields(obj.getClass())) {
        // Ei nytet staattisia kentti
        if (field != null && !java.lang.reflect.Modifier.isStatic(field.getModifiers())
                && !(field.getName().startsWith("this$") || field.getName().startsWith("_persistence"))) {
            fieldsAdded = true;
            sb.append(field.getName()).append(GenericToString.equals);
            try {
                if (field.getType().isPrimitive() || field.getType().isAssignableFrom(String.class)) {
                    if (field.getAnnotation(OmitFromToString.class) != null) {
                        sb.append(hidden_value);
                    } else {
                        sb.append(FieldUtils.readField(obj, field.getName(), true));
                    }
                } else if (field.getType().isArray()) {
                    if (!field.isAccessible()) {
                        field.setAccessible(true);
                    }
                    // TODO: Voi jatkokehitt siten ett tulostaa siististi arrayn
                    Object fieldValue = field.get(obj);
                    if (fieldValue != null) {
                        sb.append(GenericToString.na_array);
                    } else {
                        sb.append(GenericToString.null_array);
                    }
                } else {
                    addObjectInfo(sb, field, obj);
                }
            } catch (IllegalAccessException e) {
                LOGGER.error(e);
                sb.append(GenericToString.na_access);
            }

            sb.append(GenericToString.comma);
        }
    }

    if (fieldsAdded) {
        // remove last comma and space
        sb.delete(sb.length() - 2, sb.length());
    }
    sb.append(GenericToString.close_parameters);
    return sb.toString();
}

From source file:jp.co.opentone.bsol.linkbinder.dto.AbstractDto.java

/**
 * aClass???List?????./*from   ww  w.j  a  va2s .  c  o m*/
 * @param aClass
 *            class
 * @return 
 */
private List<Field> getInstanceFields(Class<?> aClass) {

    List<Field> fields = new ArrayList<Field>();
    for (Field field : aClass.getDeclaredFields()) {
        if (!Modifier.isStatic(field.getModifiers())) {
            fields.add(field);
        }
    }
    return fields;
}

From source file:io.github.benas.jpopulator.impl.PopulatorImpl.java

private boolean isStatic(Field field) {
    int fieldModifiers = field.getModifiers();
    return Modifier.isStatic(fieldModifiers);
}

From source file:com.netflix.bdp.inviso.history.TraceJobHistoryLoader.java

private void handleAttemptEvent(HistoryEvent event) throws IllegalArgumentException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    TaskAttempt attempt = new TaskAttempt();

    for (Field f : event.getDatum().getClass().getFields()) {
        f.setAccessible(true);/*from w  ww. ja  v a2 s  .c o  m*/

        if (Modifier.isStatic(f.getModifiers())) {
            continue;
        }

        String name = f.getName();
        Object value = f.get(event.getDatum());

        if (skipElements.contains(name)) {
            continue;
        }

        if (value instanceof CharSequence) {
            value = value.toString();
        }

        if (value == null || value.toString().trim().isEmpty()) {
            continue;
        }

        if ("counters".equals(name)) {
            Method m = event.getClass().getDeclaredMethod("getCounters", new Class[0]);
            m.setAccessible(true);

            Counters counters = (Counters) m.invoke(event, new Object[0]);
            value = handleCounterEntries(counters);
        }

        attempt.put(name, value);
    }

    Task task = job.getTask("taskid");
    task.getAttempt((String) attempt.get("attemptId")).merge(attempt);
}

From source file:com.chinamobile.bcbsp.util.ObjectSizer.java

/**
 * Calculate the size of the object takes up space.
 * This object is an array or object.//from w  w w  . j a  v  a 2 s .c  o  m
 *
 * @param object An object
 * @return The size of the object takes up space
 */
@SuppressWarnings("unchecked")
private int calculate(Object object) {
    if (object == null) {
        return 0;
    }
    Ref r = new Ref(object);
    if (dedup.contains(r)) {
        return 0;
    }
    dedup.add(r);
    int varSize = 0;
    int objSize = 0;
    for (Class clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
        if (clazz.isArray()) {
            varSize += emptyArrayVarSize;
            Class<?> componentType = clazz.getComponentType();
            if (componentType.isPrimitive()) {
                varSize += lengthOfPrimitiveArray(object) * sizeofPrimitiveClass(componentType);
                return occupationSize(emptyObjectSize, varSize, 0);
            }

            Object[] array = (Object[]) object;
            varSize += nullReferenceSize * array.length;
            for (Object o : array) {
                objSize += calculate(o);
            }
            return occupationSize(emptyObjectSize, varSize, objSize);
        }

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (Modifier.isStatic(field.getModifiers())) {
                continue;
            }
            if (clazz != field.getDeclaringClass()) {
                continue;
            }
            Class<?> type = field.getType();
            if (type.isPrimitive()) {
                varSize += sizeofPrimitiveClass(type);
            } else {
                varSize += nullReferenceSize;
                try {
                    field.setAccessible(true);
                    objSize += calculate(field.get(object));
                } catch (Exception e) {
                    LOG.error("[calculate]", e);
                    objSize += occupyofConstructor(object, field);
                }
            }
        }
    }
    return occupationSize(emptyObjectSize, varSize, objSize);
}

From source file:com.netflix.bdp.inviso.history.TraceJobHistoryLoader.java

private void handleTaskEvent(HistoryEvent event) throws IllegalArgumentException, IllegalAccessException,
        NoSuchMethodException, InvocationTargetException {
    Task task = new Task();

    for (Field f : event.getDatum().getClass().getFields()) {
        f.setAccessible(true);//from   w  w w.j  ava  2s  .co  m

        if (Modifier.isStatic(f.getModifiers())) {
            continue;
        }

        String name = f.getName();
        Object value = f.get(event.getDatum());

        if (skipElements.contains(name)) {
            continue;
        }

        if (value instanceof CharSequence) {
            value = value.toString();
        }

        if (value == null || value.toString().trim().isEmpty()) {
            continue;
        }

        if ("counters".equals(name)) {
            Method m = event.getClass().getDeclaredMethod("getCounters", new Class[0]);
            m.setAccessible(true);

            Counters counters = (Counters) m.invoke(event, new Object[0]);
            value = handleCounterEntries(counters);
        }

        task.put(name, value);
    }

    String taskId = (String) task.get("taskid");

    job.getTask(taskId).merge(task);
}

From source file:org.apache.hawq.pxf.plugins.hdfs.WritableResolver.java

/**
 * Constructs a WritableResolver./*from www.j  a v  a 2  s. c  o m*/
 *
 * @param input all input parameters coming from the client
 * @throws Exception if schema file is missing, cannot be found in
 *                   classpath or fails to instantiate
 */
public WritableResolver(InputData input) throws Exception {
    super(input);

    String schemaName = inputData.getUserProperty("DATA-SCHEMA");

    /** Testing that the schema name was supplied by the user - schema is an optional property. */
    if (schemaName == null) {
        throw new DataSchemaException(SCHEMA_NOT_INDICATED, this.getClass().getName());
    }

    /** Testing that the schema resource exists. */
    if (!isSchemaOnClasspath(schemaName)) {
        throw new DataSchemaException(SCHEMA_NOT_ON_CLASSPATH, schemaName);
    }

    userObject = Utilities.createAnyInstance(schemaName);
    fields = userObject.getClass().getDeclaredFields();
    recordkeyIndex = (inputData.getRecordkeyColumn() == null) ? RECORDKEY_UNDEFINED
            : inputData.getRecordkeyColumn().columnIndex();

    // fields details:
    if (LOG.isDebugEnabled()) {
        for (int i = 0; i < fields.length; i++) {
            Field field = fields[i];
            String javaType = field.getType().getName();
            boolean isPrivate = Modifier.isPrivate(field.getModifiers());

            LOG.debug("Field #" + i + ", name: " + field.getName() + " type: " + javaType + ", "
                    + (isArray(javaType) ? "Array" : "Primitive") + ", "
                    + (isPrivate ? "Private" : "accessible") + " field");
        }
    }
}

From source file:de.taimos.dvalin.jaxrs.remote.RemoteServiceBeanPostProcessor.java

private InjectionMetadata buildResourceMetadata(Class<?> clazz) {
    LinkedList<InjectionMetadata.InjectedElement> elements = new LinkedList<InjectionMetadata.InjectedElement>();
    Class<?> targetClass = clazz;

    do {/*from  ww  w . j av a 2 s.com*/
        LinkedList<InjectionMetadata.InjectedElement> currElements = new LinkedList<InjectionMetadata.InjectedElement>();
        for (Field field : targetClass.getDeclaredFields()) {
            if (field.isAnnotationPresent(RemoteService.class)) {
                if (Modifier.isStatic(field.getModifiers())) {
                    throw new IllegalStateException(
                            "@RemoteService annotation is not supported on static fields");
                }
                currElements.add(new RemoteServiceElement(field, field, null));
            }
        }
        for (Method method : targetClass.getDeclaredMethods()) {
            Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
            if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                continue;
            }
            if (method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                if (bridgedMethod.isAnnotationPresent(RemoteService.class)) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        throw new IllegalStateException(
                                "@RemoteService annotation is not supported on static methods");
                    }
                    if (method.getParameterTypes().length != 1) {
                        throw new IllegalStateException(
                                "@RemoteService annotation requires a single-arg method: " + method);
                    }
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new RemoteServiceElement(method, bridgedMethod, pd));
                }
            }
        }
        elements.addAll(0, currElements);
        targetClass = targetClass.getSuperclass();
    } while ((targetClass != null) && (targetClass != Object.class));

    return new InjectionMetadata(clazz, elements);
}

From source file:com.holonplatform.core.internal.property.DefaultPropertySetRefIntrospector.java

@Override
public PropertySet<?> getPropertySet(PropertySetRef annotation) throws PropertySetIntrospectionException {
    ObjectUtils.argumentNotNull(annotation, "PropertySetRef annotation must be not null");

    // reference class
    final Class<?> cls = annotation.value();
    if (cls == null) {
        throw new PropertySetIntrospectionException("[PropertySetRef] missing value");
    }//w  w  w. ja va 2 s .  com

    // field name
    String fieldName = AnnotationUtils.getStringValue(annotation.field());

    boolean wasNullFieldName = (fieldName == null);

    if (fieldName == null) {

        // check cache
        synchronized (cache) {
            final CacheKey key = new CacheKey(cls, null);
            if (cache.containsKey(key)) {
                return cache.get(key);
            }
        }

        if (PropertySet.class == cls) {
            throw new PropertySetIntrospectionException(
                    "Invalid PropertySetRef class value: [" + cls.getName() + "]");
        }

        // If the class itself is a PropertySet, try to instantiate it
        if (PropertySet.class.isAssignableFrom(cls)) {
            try {
                return (PropertySet<?>) cls.newInstance();
            } catch (InstantiationException | IllegalAccessException e) {
                throw new PropertySetIntrospectionException(
                        "[PropertySetRef] Failed to instantiate PropertySet class [" + cls.getName() + "]", e);
            }
        }

        // Look for a public static PropertySet type field
        List<String> candidateFieldNames = new LinkedList<>();
        Field[] flds = cls.getDeclaredFields();
        if (flds != null) {
            for (Field fld : flds) {
                if (Modifier.isStatic(fld.getModifiers()) && Modifier.isPublic(fld.getModifiers())
                        && PropertySet.class.isAssignableFrom(fld.getType())) {
                    candidateFieldNames.add(fld.getName());
                }
            }
        }

        if (candidateFieldNames.isEmpty()) {
            throw new PropertySetIntrospectionException(
                    "[PropertySetRef] Cannot find any valid public static PropertySet type field in class ["
                            + cls.getName() + "]");
        }

        if (candidateFieldNames.size() > 1) {
            throw new PropertySetIntrospectionException(
                    "[PropertySetRef] More than one valid PropertySet type field found in class ["
                            + cls.getName()
                            + "]: please specify the field name to use in PropertySetRef annotation. Detected PropertySet fields: ["
                            + candidateFieldNames + "]");
        }

        fieldName = candidateFieldNames.get(0);

    } else {

        // check cache
        synchronized (cache) {
            final CacheKey key = new CacheKey(cls, fieldName);
            if (cache.containsKey(key)) {
                return cache.get(key);
            }
        }

    }

    if (LOGGER.isEnabled(Level.DEBUG)) {
        final String fn = fieldName;
        LOGGER.debug(() -> "Get PropertySet using PropertySetRef annotation for class [" + cls
                + "] and field name [" + fn + "]");
    }

    // Read the PropertySet field
    try {
        Object value = FieldUtils.readStaticField(cls, fieldName);

        if (value == null) {
            throw new PropertySetIntrospectionException("[PropertySetRef] The field [" + fieldName
                    + "] in class [" + cls.getName() + "] has null value");
        }

        if (!PropertySet.class.isAssignableFrom(value.getClass())) {
            throw new PropertySetIntrospectionException(
                    "[PropertySetRef] The field [" + fieldName + "] in class [" + cls.getName()
                            + "] is not of PropertySet type but [" + value.getClass().getName() + "]");
        }

        final PropertySet<?> propertySet = (PropertySet<?>) value;

        // put in cache and return
        if (wasNullFieldName) {
            cache.putIfAbsent(new CacheKey(cls, null), propertySet);
        }
        PropertySet<?> existing = cache.putIfAbsent(new CacheKey(cls, fieldName), propertySet);
        return (existing != null ? existing : propertySet);

    } catch (IllegalAccessException e) {
        throw new PropertySetIntrospectionException(
                "[PropertySetRef] Failed to read field [" + fieldName + "] from class [" + cls.getName() + "]",
                e);
    }
}

From source file:org.mayocat.search.elasticsearch.AbstractGenericEntityIndexDocumentPurveyor.java

protected Map<String, Object> extractSourceFromEntity(Entity entity, Tenant tenant) {
    Map<String, Object> source = Maps.newHashMap();
    Map<String, Object> properties = Maps.newHashMap();

    boolean hasClassLevelIndexAnnotation = entity.getClass().isAnnotationPresent(Index.class);

    for (Field field : entity.getClass().getDeclaredFields()) {
        boolean isAccessible = field.isAccessible();
        try {/*from w  w w .  jav a  2s . co m*/
            if (Modifier.isStatic(field.getModifiers())) {
                // we're not interested in static fields like serialVersionUid (or any other static field)
                continue;
            }

            if (Identifiable.class.isAssignableFrom(entity.getClass()) && field.getName().equals("id")) {
                // do not index the id of identifiable under properties
                continue;
            }

            if (Slug.class.isAssignableFrom(entity.getClass()) && field.getName().equals("slug")) {
                // do not index the slug of slugs under properties
                // (it is indexed as a top level property)
                continue;
            }

            field.setAccessible(true);
            boolean searchIgnoreFlag = field.isAnnotationPresent(DoNotIndex.class);
            boolean indexFlag = field.isAnnotationPresent(Index.class);

            if ((hasClassLevelIndexAnnotation || indexFlag) && !searchIgnoreFlag) {
                if (field.get(entity) != null) {
                    Class fieldClass = field.get(entity).getClass();

                    if (isAddonField(fieldClass, field)) {

                        // Treat addons differently.
                        // They're not located in the "properties" object like the other entity properties,
                        // but they're stored in their own "addon" object

                        Association<Map<String, AddonGroup>> addons = (Association<Map<String, AddonGroup>>) field
                                .get(entity);
                        if (addons.isLoaded()) {
                            source.put("addons", extractAddons(addons.get()));
                        }
                    } else if (BigDecimal.class.isAssignableFrom(fieldClass)) {

                        // Convert big decimal to double value

                        properties.put(field.getName(), ((BigDecimal) field.get(entity)).doubleValue());
                    } else {

                        // General case o>

                        properties.put(field.getName(), field.get(entity));
                    }
                } else {
                    properties.put(field.getName(), null);
                }
            }
        } catch (IllegalAccessException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonMappingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonParseException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (JsonProcessingException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } catch (IOException e) {
            this.logger.error("Error extracting entity", entity.getSlug(), e);
        } finally {
            field.setAccessible(isAccessible);
        }
    }

    source.put("properties", properties);

    if (HasFeaturedImage.class.isAssignableFrom(entity.getClass())) {
        HasFeaturedImage hasFeaturedImage = (HasFeaturedImage) entity;
        if (hasFeaturedImage.getFeaturedImageId() != null) {
            Attachment attachment = attachmentStore.findAndLoadById(hasFeaturedImage.getFeaturedImageId());
            if (attachment != null) {
                Map<String, Object> imageMap = Maps.newHashMap();
                imageMap.put("url", entityURLFactory.create(attachment, tenant));
                imageMap.put("title", attachment.getTitle());
                imageMap.put("extension", attachment.getExtension());
                source.put("featuredImage", imageMap);
            }
        }
    }

    source.put("url", entityURLFactory.create(entity, tenant).toString());
    source.put("api_url", entityURLFactory.create(entity, tenant, URLType.API).toString());
    source.put("slug", entity.getSlug());

    return source;
}