Example usage for java.lang.reflect Field getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the field represented by this Field object.

Usage

From source file:com.changhong.util.db.util.sql.UpdateSqlBuilder.java

/**
 * ,?/*  w w  w. j av  a2s  .  com*/
 * 
 * @return
 * @throws CHDBException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static CHArrayList getFieldsAndValue(Object entity)
        throws CHDBException, IllegalArgumentException, IllegalAccessException {
    // TODO Auto-generated method stub
    CHArrayList arrayList = new CHArrayList();
    if (entity == null) {
        throw new CHDBException("?");
    }
    Class<?> clazz = entity.getClass();
    Field[] fields = clazz.getDeclaredFields();
    for (Field field : fields) {

        if (!DBUtils.isTransient(field)) {
            if (DBUtils.isBaseDateType(field)) {
                CHPrimaryKey annotation = field.getAnnotation(CHPrimaryKey.class);
                if (annotation == null || !annotation.autoIncrement()) {
                    String columnName = DBUtils.getColumnByField(field);
                    columnName = (columnName != null && !columnName.equals("")) ? columnName : field.getName();
                    field.setAccessible(true);
                    String val = DBUtils.toString(field.get(entity));
                    arrayList.add(columnName, val);
                }
            }
        }
    }
    return arrayList;
}

From source file:com.iisigroup.cap.utils.CapBeanUtil.java

public static <T> T setField(T entry, String fieldId, Object value) {
    Field field = ReflectionUtils.findField(entry.getClass(), fieldId);
    if (field != null) {
        String setter = new StringBuffer("set").append(String.valueOf(field.getName().charAt(0)).toUpperCase())
                .append(field.getName().substring(1)).toString();
        Method method = ReflectionUtils.findMethod(entry.getClass(), setter, new Class[] { field.getType() });
        if (method != null) {
            try {
                if (field.getType() != String.class && "".equals(value)) {
                    value = null;/*from  w  w w.  j  a va 2 s . com*/
                } else if (field.getType() == BigDecimal.class) {
                    value = CapMath.getBigDecimal(String.valueOf(value));
                } else if (value instanceof String) {
                    if (field.getType() == java.util.Date.class || field.getType() == java.sql.Date.class) {
                        value = CapDate.parseDate((String) value);
                    } else if (field.getType() == Timestamp.class) {
                        value = CapDate.convertStringToTimestamp1((String) value);
                    }
                }
                if (value == null) {
                    method.invoke(entry, new Object[] { null });
                } else {
                    method.invoke(entry, ConvertUtils.convert(value, field.getType()));
                }
            } catch (Exception e) {
                if (LOGGER.isTraceEnabled()) {
                    LOGGER.trace(e.getMessage());
                } else {
                    LOGGER.warn(e.getMessage(), e);
                }
            }
        }
    }
    return entry;
}

From source file:com.browseengine.bobo.serialize.JSONSerializer.java

private static void dumpObject(JSONObject jsonObj, Field f, JSONSerializable srcObj)
        throws JSONSerializationException, JSONException {
    Object value;//from w w w  .j  a v  a  2s  .  com
    try {
        value = f.get(srcObj);
    } catch (Exception e) {
        throw new JSONSerializationException(e.getMessage(), e);
    }

    Class type = f.getType();

    String name = f.getName();

    if (type.isPrimitive()) {
        jsonObj.put(name, String.valueOf(value));
    } else if (type == String.class) {
        if (value != null) {
            jsonObj.put(name, String.valueOf(value));
        }
    } else if (JSONSerializable.class.isInstance(value)) {
        jsonObj.put(name, serializeJSONObject((JSONSerializable) value));
    }
}

From source file:nz.co.senanque.validationengine.ValidationUtils.java

public static void setDefaults(ValidationObject object) {
    for (Field field : object.getClass().getDeclaredFields()) {
        XmlElement xmlElement = field.getAnnotation(XmlElement.class);
        if (xmlElement != null && hasText(xmlElement.defaultValue())) {
            String value = xmlElement.defaultValue();
            Method setter = figureSetter(field.getName(), object.getClass());
            Class<?> type = setter.getParameterTypes()[0];
            try {
                setter.invoke(object, ConvertUtils.convertToObject(type, value, null));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }// ww  w .  j  a  va 2  s  .  co  m
        }
        String n = field.getName();
        if (n.startsWith("m_")) {
            n = n.substring(2);
        }
        try {
            Method getter = figureGetter(n, object.getClass());
            Annotation unknown = getter.getAnnotation(Unknown.class);
            if (unknown != null) {
                object.getMetadata().addUnknown(field.getName());
            }
        } catch (RuntimeException e) {
            // ignore
        }
    }
}

From source file:com.qingstor.sdk.utils.QSJSONUtil.java

private static boolean initParameter(JSONObject o, Field[] declaredField, Class objClass, Object targetObj)
        throws NoSuchMethodException {
    boolean hasParam = false;
    for (Field field : declaredField) {
        String methodField = QSParamInvokeUtil.capitalize(field.getName());
        String getMethodName = field.getType() == Boolean.class ? "is" + methodField : "get" + methodField;
        String setMethodName = "set" + methodField;
        Method[] methods = objClass.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(getMethodName)) {
                ParamAnnotation annotation = m.getAnnotation(ParamAnnotation.class);
                if (annotation == null) {
                    continue;
                }/*from www  .j  av a2 s . c  om*/
                String dataKey = annotation.paramName();

                if (o.has(dataKey)) {
                    hasParam = true;
                    Object data = toObject(o, dataKey);
                    Method setM = objClass.getDeclaredMethod(setMethodName, field.getType());
                    setParameterToMap(setM, targetObj, field, data);
                }
            }
        }
    }
    return hasParam;
}

From source file:com.plusub.lib.annotate.JsonParserUtils.java

/**
 * /*  w w w .j  av a2 s. co  m*/
 * <p>Title: setFieldValue
 * <p>Description: 
 * @param object 
 * @param field 
 * @param value 
 */
private static void setFieldValue(Object object, Field field, Object value) {
    Object ov = null;
    try {
        ov = getType(field, value, field.getName());
        field.set(object, ov);
    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        if (showLog) {
            e.printStackTrace();
        }

        //fieldset
        try {
            Method m = object.getClass().getMethod(getSetMethodName(field), field.getType());
            if (m != null) {
                m.invoke(object, ov);
            }
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            if (showLog) {
                Logger.e(TAG,
                        "set field value fail field:" + field.getName() + " method:" + getSetMethodName(field));
                e1.printStackTrace();
            }
        }
    } catch (IllegalArgumentException e) {
        // TODO Auto-generated catch block
        if (showLog) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        if (showLog) {
            e.printStackTrace();
        }
    }
}

From source file:fr.paris.lutece.util.bean.BeanUtil.java

/**
 * Populate a bean using parameters in http request
 * /*ww  w . j av a  2  s  .com*/
 * @param bean bean to populate
 * @param request http request
 */
public static void populate(Object bean, HttpServletRequest request) {
    for (Field field : bean.getClass().getDeclaredFields()) {
        try {
            // for all boolean field, init to false
            if (field.getType().getName().equals(Boolean.class.getName())
                    || field.getType().getName().equals(boolean.class.getName())) {
                field.setAccessible(true);
                field.set(bean, false);
            }
        } catch (Exception e) {
            String error = "La valeur du champ " + field.getName() + " de la classe "
                    + bean.getClass().getName() + " n'a pas pu tre rcupr ";
            AppLogService.error(error);
            throw new RuntimeException(error, e);
        }
    }

    try {
        BeanUtils.populate(bean, convertMap(request.getParameterMap()));
    } catch (IllegalAccessException e) {
        AppLogService.error("Unable to fetch data from request", e);
    } catch (InvocationTargetException e) {
        AppLogService.error("Unable to fetch data from request", e);
    }
}

From source file:it.nicola_amatucci.util.Json.java

public static <T> JSONObject json_from_object(Object o, Class<T> objClass) throws Exception {
    JSONObject json = new JSONObject();
    Field[] fields = objClass.getFields();
    try {/*from w  w  w  . j  a v  a 2s.  c  o m*/
        for (Field field : fields) {
            //valore del campo
            try {
                String typeName = field.getType().getSimpleName();

                //in base al tipo richiamo l'opportuna funzione
                if (typeName.equals("String") || typeName.equals("boolean") || typeName.equals("int")
                        || typeName.equals("long") || typeName.equals("double")) {
                    json.put(field.getName(), objClass.getField(field.getName()).get(o));
                } else if (typeName.equals("Date")) {
                    json.put(field.getName(), new SimpleDateFormat(Json.DATA_FORMAT)
                            .format((java.util.Date) objClass.getField(field.getName()).get(o)));
                } else if (field.getType().isArray()) {
                    try {
                        JSONArray array = new JSONArray();

                        Class c = Class.forName(field.getType().getName()).getComponentType();
                        Object[] objArray = (Object[]) objClass.getField(field.getName()).get(o);
                        for (int i = 0; i < objArray.length; i++) {
                            array.put(json_from_object(objArray[i], c));
                        }
                        json.put(field.getName(), array);
                    } catch (Exception e) {
                        throw e;
                    }
                } else {
                    JSONObject jsonObj = json_from_object(objClass.getField(field.getName()).get(o),
                            field.getType());
                    json.put(field.getName(), jsonObj);
                }

            } catch (Exception e) {
                throw e;
            }

        }
    } catch (Exception e) {
        throw e;
    }

    return json;
}

From source file:com.smart.utils.ReflectionUtils.java

/**
 * ?classString,list,listString//from  ww  w.  j  a va2 s  .  c  om
 * 
 * @param clz
 * @return
 */
public static List<String> getAllFieldNames(Class clz) {
    List result = new ArrayList();
    Map allFields = new HashMap();
    // ???
    List classFamilyTree = new LinkedList();
    classFamilyTree.add(clz);
    Class tempSuperClass = clz;
    while ((tempSuperClass = tempSuperClass.getSuperclass()) != null) {
        classFamilyTree.add(tempSuperClass);
    }
    // Map???field??????
    for (int i = classFamilyTree.size() - 1; i >= 0; i--) {
        Class tempClass = (Class) classFamilyTree.get(i);
        Field[] fieldsOfTempClass = tempClass.getDeclaredFields();
        for (int j = 0; j < fieldsOfTempClass.length; j++) {
            Field field = fieldsOfTempClass[j];
            allFields.put(field.getName(), field.getName());
        }
    }
    // map?list
    for (Iterator iter = allFields.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        result.add(entry.getValue());
    }
    return result;
}

From source file:com.smart.utils.ReflectionUtils.java

/**
 * ?classFieldlistlistField//from  w ww .  ja v a  2 s .  co  m
 * 
 * @param clz
 * @return
 */
public static List<Field> getAllFields(Class clz) {
    List result = new ArrayList();
    Map allFields = new HashMap();
    // ???
    List classFamilyTree = new LinkedList();
    classFamilyTree.add(clz);
    Class tempSuperClass = clz;
    while ((tempSuperClass = tempSuperClass.getSuperclass()) != null) {
        classFamilyTree.add(tempSuperClass);
    }
    // Map???field??????
    for (int i = classFamilyTree.size() - 1; i >= 0; i--) {
        Class tempClass = (Class) classFamilyTree.get(i);
        Field[] fieldsOfTempClass = tempClass.getDeclaredFields();
        for (int j = 0; j < fieldsOfTempClass.length; j++) {
            Field field = fieldsOfTempClass[j];
            allFields.put(field.getName(), field);
        }
    }

    // map?list
    for (Iterator iter = allFields.entrySet().iterator(); iter.hasNext();) {
        Map.Entry entry = (Map.Entry) iter.next();
        result.add(entry.getValue());
    }
    return result;
}