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:Main.java

public static <C> C cloneObject(C original) {
    try {//from  ww  w  . j  ava 2  s.  com
        C clone = (C) original.getClass().newInstance();
        for (Field field : getAllFieldsValues(original.getClass())) {
            field.setAccessible(true);
            if (field.get(original) == null || Modifier.isFinal(field.getModifiers())) {
                continue;
            }
            if (field.getType().isPrimitive() || field.getType().equals(String.class)
                    || field.getType().getSuperclass().equals(Number.class)
                    || field.getType().equals(Boolean.class)) {
                field.set(clone, field.get(original));
            } else {
                Object childObj = field.get(original);
                if (childObj == original) {
                    field.set(clone, clone);
                } else {
                    field.set(clone, cloneObject(field.get(original)));
                }
            }
        }
        return clone;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.feilong.core.lang.reflect.FieldUtil.java

/**
 *  <code>klass</code> ? <code>excludeFieldNames</code> ?list.
 *
 * @param klass//from   w  w  w  .j av a2 s.c o m
 *            the klass
 * @param excludeFieldNames
 *            ?field names,?nullOrEmpty ?
 * @return  <code>obj</code> null, {@link NullPointerException}<br>
 *          {@link FieldUtils#getAllFieldsList(Class)} nullempty, {@link Collections#emptyList()}<br>
 * @see FieldUtils#getAllFieldsList(Class)
 * @since 1.7.1
 */
//no static
public static List<Field> getAllFieldList(final Class<?> klass, String... excludeFieldNames) {
    // {@link Field},parents, public/protect/private/inherited...
    List<Field> fieldList = FieldUtils.getAllFieldsList(klass);
    if (isNullOrEmpty(fieldList)) {
        return Collections.emptyList();
    }
    //**********************************************************************************************
    Predicate<Field> excludeFieldPredicate = BeanPredicateUtil.containsPredicate("name", excludeFieldNames);
    Predicate<Field> staticPredicate = new Predicate<Field>() {

        @Override
        public boolean evaluate(Field field) {
            int modifiers = field.getModifiers();
            // ??? log   serialVersionUID
            boolean isStatic = Modifier.isStatic(modifiers);

            String pattern = "[{}.{}],modifiers:[{}]{}";
            LOGGER.trace(pattern, klass.getSimpleName(), field.getName(), modifiers,
                    isStatic ? " [isStatic]" : EMPTY);
            return isStatic;
        }
    };
    return CollectionsUtil.selectRejected(fieldList,
            PredicateUtils.orPredicate(excludeFieldPredicate, staticPredicate));
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public Map<Field, Column> buildEntityFieldColumnMap(Class<? extends DalEntity> entityClass) {
    Map<Field, Column> columnByField = new LinkedHashMap<Field, Column>();

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            fld.setAccessible(true);//from   w  ww . j a v  a 2s  . c  o  m
            columnByField.put(fld, column);
        }
    }

    return columnByField;
}

From source file:com.blackducksoftware.integration.hub.detect.workflow.report.util.ObjectPrinter.java

public static void populateField(final Field field, final String prefix, final Object guy,
        Map<String, String> fieldMap) {
    if (java.lang.reflect.Modifier.isStatic(field.getModifiers())) {
        return; // don't print static fields.
    }//  www  . j a  v a 2  s . c o m
    final String name = field.getName();
    String value = "unknown";
    Object obj = null;
    try {
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        obj = field.get(guy);
    } catch (final Exception e) {
        e.printStackTrace();
    }
    boolean shouldPrintObjectsFields = false;
    if (obj == null) {
        value = "null";
    } else {
        value = obj.toString();
        shouldPrintObjectsFields = shouldRecursivelyPrintType(obj.getClass());
    }
    if (!shouldPrintObjectsFields) {
        if (StringUtils.isBlank(prefix)) {
            fieldMap.put(name, value);
        } else {
            fieldMap.put(prefix + "." + name, value);
        }
    } else {
        String nestedPrefix = name;
        if (StringUtils.isNotBlank(prefix)) {
            nestedPrefix = prefix + "." + nestedPrefix;
        }
        populateObject(nestedPrefix, obj, fieldMap);
    }

}

From source file:no.abmu.util.reflection.FieldUtil.java

public static Object getFieldValue(Object obj, String fieldName) {
    Assert.checkRequiredArgument("obj", obj);
    Assert.checkRequiredArgument("fieldName", fieldName);
    String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '"
            + fieldName + "'";
    Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName));

    Field field = getField(obj, fieldName);

    Object value = null;/*from   ww  w  .  ja va  2  s  .  c  o m*/
    try {
        if (Modifier.isPublic(field.getModifiers())) {
            value = field.get(obj);
        } else {
            field.setAccessible(true);
            value = field.get(obj);
            field.setAccessible(false);
        }
    } catch (IllegalAccessException e) {
        logger.error(e.getMessage());
    }

    return value;
}

From source file:edu.wright.daselab.linkgen.ConfigurationParams.java

public final static boolean checkStatusOnLoad() throws Exception {
    // using reflection to check all properties/params fields.
    // you can use annotation for better retrieval
    // http://stackoverflow.com/questions/2020202/pitfalls-in-getting-member-variable-values-in-java-with-reflection
    // by this time, none of the values are empty.
    String name = "";
    String value = "";
    logger.info("Displaying all param values:");
    boolean isFine = true;
    Field[] fields = ConfigurationParams.class.getDeclaredFields();
    for (Field field : fields) {
        // check only final static fields
        if (!Modifier.isFinal((field.getModifiers())) || (!Modifier.isStatic(field.getModifiers()))) {
            continue;
        }//from  ww w.  j a v  a 2  s. c  o  m
        name = field.getName();
        try {
            value = (String) field.get(null).toString();
        } catch (Exception e) {
            Monitor.error(Error.INVALID_CONFIG_PARAMS.toString());
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
        }
        if ((value == null) || value.toString().trim().equals("")) {
            isFine = false;
        }
        String status = isFine ? "OK" : "Failed";
        logger.info(status + " \t" + name + "=" + value);
        if (!isFine)
            throw new IllegalArgumentException(Error.INVALID_CONFIG_PARAMS.toString());
    }
    return isFine;
}

From source file:no.abmu.util.reflection.FieldUtil.java

public static boolean setFieldValue(Object obj, String fieldName, Object value) {
    Assert.checkRequiredArgument("obj", obj);
    Assert.checkRequiredArgument("fieldName", fieldName);
    String errorMessage = "Object '" + obj.getClass().getName() + " does not have field/variable with name '"
            + fieldName + "'";
    Assert.assertTrue(errorMessage, hasObjectVariable(obj, fieldName));

    Field field = getField(obj, fieldName);

    boolean sucess = false;
    try {//from   www  .  j a  va  2  s  .co m
        if (Modifier.isPublic(field.getModifiers())) {
            field.set(obj, value);
        } else {
            field.setAccessible(true);
            field.set(obj, value);
            field.setAccessible(false);
        }
        sucess = true;
    } catch (IllegalAccessException e) {
        logger.warn(e.getMessage());
    }

    return sucess;
}

From source file:com.siberhus.ngai.core.CrudHelper.java

/**
 * // w w  w .  jav  a  2 s  . c o  m
 * @param entityClass
 * @return
 */
private synchronized final static EntityInfo getEntityInfo(Class<?> entityClass) {

    EntityInfo entityInfo = ENTITY_INFO_CACHE.get(entityClass);
    if (entityInfo != null) {
        return entityInfo;
    }
    entityInfo = new EntityInfo();
    Entity entityAnnot = (Entity) entityClass.getAnnotation(Entity.class);
    if (!"".equals(entityAnnot.name())) {
        entityInfo.setEntityName(entityAnnot.name());
    } else {
        entityInfo.setEntityName(entityClass.getSimpleName());
    }
    Collection<Field> entityFields = ReflectUtil.getFields(entityClass);
    for (Field field : entityFields) {
        if (Modifier.isStatic(field.getModifiers())) {
            continue;
        }
        if (field.getName().equals("id")) {
            continue;
        }
        if (!field.isAccessible()) {
            field.setAccessible(true);
        }
        entityInfo.getFieldSet().add(field);
    }
    ENTITY_INFO_CACHE.put(entityClass, entityInfo);
    return entityInfo;
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

static public void addEntityFields(Class<? extends DalEntity> entityClass, DalResponseBuilder responseBuilder) {

    responseBuilder.addResponseMeta("SCol");

    for (Field fld : entityClass.getDeclaredFields()) {
        if (!Modifier.isStatic(fld.getModifiers())) {
            Column column = fld.getAnnotation(Column.class);
            if (column != null) {

                DalResponseBuilder builder = responseBuilder.startTag("SCol");

                builder.attribute("Required", column.nullable() ? "0" : "1");

                int colSize = 11;
                Class<?> fieldType = fld.getType();
                if (String.class == fieldType) {
                    colSize = column.length();
                }//from  w w  w.  j a v a 2 s.  c om
                builder.attribute("ColSize", Integer.toString(colSize));

                builder.attribute("Description", "");

                builder.attribute("Name", column.name());

                // TODO Synchronise with the Perl DAL code
                builder.attribute("DataType", fieldType.getSimpleName().toLowerCase());

                builder.endTag();
            }
        }
    }
}

From source file:com.taobao.diamond.common.Constants.java

/** ?-D &gt; env &gt; diamond.properties  */
public static void init() {
    File diamondFile = new File(System.getProperty("user.home"), "diamond/ServerAddress");
    if (!diamondFile.exists()) {
        diamondFile.getParentFile().mkdirs();
        try (OutputStream out = new FileOutputStream(diamondFile)) {
            out.write("localhost".getBytes());
        } catch (IOException e) {
            throw new IllegalStateException(diamondFile.toString(), e);
        }/*from w w  w .ja  va 2 s .c  o m*/
    }
    List<Field> fields = new ArrayList<>();
    for (Field field : Constants.class.getDeclaredFields()) {
        if (Modifier.isPublic(field.getModifiers()) && !Modifier.isFinal(field.getModifiers())) {
            fields.add(field);
        }
    }

    Properties props = new Properties();
    {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        if (cl == null)
            cl = Constants.class.getClassLoader();
        try (InputStream in = cl.getResourceAsStream("diamond.properties")) {
            if (in != null)
                props.load(in);
        } catch (IOException e) {
            log.warn("load diamond.properties", e);
        }
    }
    props.putAll(System.getenv());
    props.putAll(System.getProperties());

    Map<String, Object> old = new HashMap<>();
    try {
        for (Field field : fields) {
            if (!props.containsKey(field.getName()))
                continue;
            old.put(field.getName(), field.get(Constants.class));

            String value = props.getProperty(field.getName());
            Class<?> clazz = field.getType();
            if (String.class.equals(clazz)) {
                field.set(Constraints.class, value);
            } else if (int.class.equals(clazz)) {
                if (value != null) {
                    field.set(Constraints.class, Integer.parseInt(value));
                }
            } else {
                throw new IllegalArgumentException(field + "  " + value + " ?");
            }
        }
    } catch (IllegalAccessException e) {
        throw new IllegalStateException(e);
    }

    setValue(old, "CONFIG_HTTP_URI_FILE", "HTTP_URI_FILE");
    setValue(old, "HTTP_URI_LOGIN", "HTTP_URI_FILE");
    setValue(old, "DAILY_DOMAINNAME", "DEFAULT_DOMAINNAME");
}