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:net.dmulloy2.ultimatearena.types.ArenaConfig.java

@Override
public Map<String, Object> serialize() {
    Map<String, Object> data = new LinkedHashMap<>();

    for (Field field : ArenaConfig.class.getDeclaredFields()) {
        try {/*  w w w  .  ja  v  a  2  s.c o m*/
            if (Modifier.isTransient(field.getModifiers()))
                continue;

            boolean accessible = field.isAccessible();

            field.setAccessible(true);

            if (field.getType().equals(Integer.TYPE)) {
                if (field.getInt(this) != 0)
                    data.put(field.getName(), field.getInt(this));
            } else if (field.getType().equals(Long.TYPE)) {
                if (field.getLong(this) != 0)
                    data.put(field.getName(), field.getLong(this));
            } else if (field.getType().equals(Boolean.TYPE)) {
                if (field.getBoolean(this))
                    data.put(field.getName(), field.getBoolean(this));
            } else if (field.getType().isAssignableFrom(Collection.class)) {
                if (!((Collection<?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(String.class)) {
                if ((String) field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            } else if (field.getType().isAssignableFrom(Map.class)) {
                if (!((Map<?, ?>) field.get(this)).isEmpty())
                    data.put(field.getName(), field.get(this));
            } else {
                if (field.get(this) != null)
                    data.put(field.getName(), field.get(this));
            }

            field.setAccessible(accessible);
        } catch (Throwable ex) {
        }
    }

    serializeCustomOptions(data);
    return data;
}

From source file:net.java.sip.communicator.impl.protocol.jabber.InfoRetreiver.java

/**
 * Load VCard for the given user./*  ww w  .j  a  va  2 s. c  om*/
 * Using the specified timeout.
 *
 * @param vcard VCard
 * @param connection XMPP connection
 * @param user the user
 * @param timeout timeout in second
 * @throws XMPPException if something went wrong during VCard loading
 */
public void load(VCard vcard, Connection connection, String user, long timeout) throws XMPPException {
    vcard.setTo(user);

    vcard.setType(IQ.Type.GET);
    PacketCollector collector = connection.createPacketCollector(new PacketIDFilter(vcard.getPacketID()));
    connection.sendPacket(vcard);

    VCard result = null;
    try {
        result = (VCard) collector.nextResult(timeout);

        if (result == null) {
            String errorMessage = "Timeout getting VCard information";
            throw new XMPPException(errorMessage,
                    new XMPPError(XMPPError.Condition.request_timeout, errorMessage));
        }

        if (result.getError() != null) {
            throw new XMPPException(result.getError());
        }
    } catch (ClassCastException e) {
        logger.error("No vcard for " + user);
    }

    if (result == null)
        result = new VCard();

    // copy loaded vcard fields in the supplied one.
    Field[] fields = VCard.class.getDeclaredFields();
    for (Field field : fields) {
        if (field.getDeclaringClass() == VCard.class && !Modifier.isFinal(field.getModifiers())) {
            try {
                field.setAccessible(true);
                field.set(vcard, field.get(result));
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Cannot set field:" + field, e);
            }
        }
    }
}

From source file:com.greenline.hrs.admin.web.war.conf.InjectBeanPostProcessor.java

private void injectPropertyToBean(final Object bean) {
    ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {

        @Override//from   w  w w .  j  av a 2s  .c  o m
        public void doWith(Field field) throws IllegalAccessException {
            InjectingProperty annotation = field.getAnnotation(InjectingProperty.class);
            if (annotation != null) {
                Object strValue = propertyConfigurer.getProperty(annotation.value());
                if (null != strValue) {
                    Object value = typeConverter.convertIfNecessary(strValue, field.getType());
                    ReflectionUtils.makeAccessible(field);
                    if (Modifier.isStatic(field.getModifiers())) {
                        field.set(null, value);
                    } else {
                        field.set(bean, value);
                    }
                }
            }
        }
    });
}

From source file:gov.nih.nci.iso21090.hibernate.tuple.IsoConstantTuplizerHelper.java

private Boolean setNullFlavor(Object parent) {

    Class klass = parent.getClass();
    Boolean allNullFlavors = true;
    if (Any.class.isAssignableFrom(klass)) {
        if (((Any) parent).getNullFlavor() == null) {
            try {
                while (klass != null && klass != Object.class) {
                    for (Field field : klass.getDeclaredFields()) {
                        if (!Modifier.isStatic(field.getModifiers())) {
                            field.setAccessible(true);
                            Object value = field.get(parent);
                            if (value == null) {
                                setNullFlavor(parent, field.getName());
                            } else {
                                if (Any.class.isAssignableFrom(value.getClass())) {
                                    if (!setNullFlavor(value))
                                        allNullFlavors = false;
                                    if (((Any) value).getNullFlavor() != null)
                                        allNullFlavors = false;
                                } else {
                                    allNullFlavors = false;
                                }//from   ww  w .j av a2s .c o m
                            }
                        }
                    }

                    klass = klass.getSuperclass();
                }
            } catch (SecurityException e) {
                throw new HibernateException(e);
            } catch (IllegalAccessException e) {
                throw new HibernateException(e);
            } catch (IllegalArgumentException e) {
                throw new HibernateException(e);
            }
            if (allNullFlavors)
                ((Any) parent).setNullFlavor(NullFlavor.NI);
        }
    }
    return allNullFlavors;
}

From source file:com.adobe.cq.wcm.core.components.internal.servlets.AdaptiveImageServletTest.java

private void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);/*from www.  j  a va  2 s  .co m*/
    // remove final modifier from field
    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
    field.set(null, newValue);
}

From source file:org.LexGrid.LexBIG.caCore.client.proxy.LexEVSProxyHelperImpl.java

/**
 * Creates a serializable copy of a given object
 *//* w  ww. j  a  v  a  2 s. c om*/
protected Object createClone(Object source) {
    try {
        Object target = source.getClass().newInstance();
        List<Field> fieldList = new ArrayList<Field>();
        getAllFields(source.getClass(), fieldList);
        for (Field field : fieldList) {
            Object obj = field.get(source);

            if (obj instanceof Integer || obj instanceof Float || obj instanceof Double
                    || obj instanceof Character || obj instanceof Long || obj instanceof Boolean
                    || obj instanceof String) {
                if (!Modifier.isStatic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
                    field.setAccessible(true);
                    field.set(target, obj);
                }
            }
        }
        return target;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.smartspaces.activity.annotation.StandardConfigurationPropertyAnnotationProcessor.java

/**
 * Injects config parameters into a given field of a given object, if the
 * field is marked with// ww  w.j  a  va2s.co  m
 * {@link io.smartspaces.activity.annotation.ConfigurationProperty}.
 *
 * @param obj
 *          object that contains the field into which config parameters will
 *          be injected
 * @param field
 *          field into which a config parameter will be injected
 * @param errors
 *          list container to accumulate errors
 * @param successes
 *          list container to accumulate successes
 */
private void processField(Object obj, Field field, List<String> errors, List<String> successes) {
    ConfigurationProperty annotation = field.getAnnotation(ConfigurationProperty.class);
    if (annotation == null) {
        return;
    }
    int initialErrorSize = errors.size();
    String fieldName = field.getName();
    if (Modifier.isFinal(field.getModifiers())) {
        errors.add(String.format("Field '%s' is marked final and may have unpredictable effects", fieldName));
    }
    String property = annotation.name();
    if (property == null || property.isEmpty()) {
        property = annotation.value();
    }
    property = property.trim();
    if (property.isEmpty()) {
        errors.add(String.format("Field '%s' has property name that is all white space or empty", fieldName));
    }

    boolean required = annotation.required();
    String delimiter = annotation.delimiter();
    boolean accessible = field.isAccessible();
    if (!accessible) {
        field.setAccessible(true);
    }
    try {
        Object value = null;
        Class<?> type = field.getType();
        if (required) {
            Object defaultValue = field.get(obj);
            boolean valueIsNotDefault = !Objects.equal(defaultValue, Defaults.defaultValue(type));
            if (valueIsNotDefault) {
                errors.add(String.format(
                        "Field '%s' into which a required property '%s' "
                                + "is to be injected already has a value: '%s', set 'required = false', "
                                + "or set the value of the property in the configuration "
                                + "(do not initialize the field directly).",
                        fieldName, property, defaultValue));
            }

            if (!configuration.containsProperty(property) && !property.isEmpty()) {
                errors.add(String.format("Field '%s' does not contain required property '%s'", fieldName,
                        property));
            }
        }

        // If value is required but not present, an error has already been
        // registered.
        if (type == int.class || type == Integer.class) {
            value = configuration.getPropertyInteger(property, null);
        } else if (type == long.class || type == Long.class) {
            value = configuration.getPropertyLong(property, null);
        } else if (type == double.class || type == Double.class) {
            value = configuration.getPropertyDouble(property, null);
        } else if (type == boolean.class || type == Boolean.class) {
            value = configuration.getPropertyBoolean(property, null);
        } else if (type == String.class) {
            value = configuration.getPropertyString(property);
        } else if (type.isAssignableFrom(List.class)) {
            value = configuration.getPropertyStringList(property, delimiter);
        } else if (type.isAssignableFrom(Set.class)) {
            value = configuration.getPropertyStringSet(property, delimiter);
        } else {
            errors.add(String.format(String.format("Field '%s' has unsupported type '%s'", fieldName,
                    tryGetValueForErrorMessage(property))));
        }
        if (errors.size() != initialErrorSize) {
            return;
        }
        String header = "@" + ConfigurationProperty.class.getSimpleName();
        if (value != null) {
            successes.add(String.format("%s field '%s' injected property '%s' with value '%s'", header,
                    fieldName, property, value));
            field.set(obj, value);
        } else {
            successes.add(String.format("%s field '%s' has no value from property '%s', skipping", header,
                    fieldName, property));
        }
    } catch (IllegalAccessException e) {
        errors.add(String.format("Field '%s' can not be accessed: %s", fieldName, e.toString()));
    } catch (Exception e) {
        errors.add(String.format("Field '%s' with property '%s' encountered error: %s", fieldName,
                tryGetValueForErrorMessage(property), e.toString()));
    } finally {
        if (!accessible) {
            field.setAccessible(false);
        }
    }
}

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

/**
 * Sets customWritable fields and creates a OneRow object.
 *///from   w  w w .  j  a va  2s.  c o  m
@Override
public OneRow setFields(List<OneField> record) throws Exception {
    Writable key = null;

    int colIdx = 0;
    for (Field field : fields) {
        /*
         * extract recordkey based on the column descriptor type
         * and add to OneRow.key
         */
        if (colIdx == recordkeyIndex) {
            key = recordkeyAdapter.convertKeyValue(record.get(colIdx).val);
            colIdx++;
        }

        if (Modifier.isPrivate(field.getModifiers())) {
            continue;
        }

        String javaType = field.getType().getName();
        convertJavaToGPDBType(javaType);
        if (isArray(javaType)) {
            Object value = field.get(userObject);
            int length = Array.getLength(value);
            for (int j = 0; j < length; j++, colIdx++) {
                Array.set(value, j, record.get(colIdx).val);
            }
        } else {
            field.set(userObject, record.get(colIdx).val);
            colIdx++;
        }
    }

    return new OneRow(key, userObject);
}

From source file:com.haulmont.cuba.core.sys.MetadataLoader.java

/**
 * Guesses id for a datatype registered in legacy datatypes.xml file.
 * For backward compatibility only.//from  w ww.  ja  va 2 s.  c  o m
 */
protected String guessDatatypeId(Datatype datatype) {
    if (datatype instanceof BigDecimalDatatype)
        return "decimal";
    if (datatype instanceof BooleanDatatype)
        return "boolean";
    if (datatype instanceof ByteArrayDatatype)
        return "byteArray";
    if (datatype instanceof DateDatatype)
        return "date";
    if (datatype instanceof DateTimeDatatype)
        return "dateTime";
    if (datatype instanceof DoubleDatatype)
        return "double";
    if (datatype instanceof IntegerDatatype)
        return "int";
    if (datatype instanceof LongDatatype)
        return "long";
    if (datatype instanceof StringDatatype)
        return "string";
    if (datatype instanceof TimeDatatype)
        return "time";
    if (datatype instanceof UUIDDatatype)
        return "uuid";
    try {
        Field nameField = datatype.getClass().getField("NAME");
        if (Modifier.isStatic(nameField.getModifiers()) && nameField.isAccessible()) {
            return (String) nameField.get(null);
        }
    } catch (Exception e) {
        log.trace("Cannot get NAME static field value: " + e);
    }
    throw new IllegalStateException("Cannot guess id for datatype " + datatype);
}

From source file:com.qmetry.qaf.automation.data.BaseDataBean.java

/**
 * @param fieldName//  w  w w.j a  v  a 2s  .c o m
 *            case insensitive field name
 * @param value
 */
public void fillData(String fieldName, String value) {
    Field[] fields = getFields();// this.getClass().getDeclaredFields();
    for (Field field2 : fields) {
        Field field = field2;
        if (field.getName().equalsIgnoreCase(fieldName)) {
            if (!(Modifier.isFinal(field.getModifiers()))) {
                setField(field, value);
            }
            return;
        }
    }
}