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.alibaba.rocketmq.common.MixAll.java

/**
 * ??Properties/*www . ja  v a2  s  . c  o  m*/
 */
public static Properties object2Properties(final Object object) {
    Properties properties = new Properties();

    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                }

                if (value != null) {
                    properties.setProperty(name, value.toString());
                }
            }
        }
    }

    return properties;
}

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

/**
 * ?set??/*from  w ww. jav  a2s  .c  o m*/
 * <p>Title: getSetMethodName
 * <p>Description: 
 * @param field
 * @return
 */
private static String getSetMethodName(Field field) {
    Class clazz = field.getType();
    String name = field.getName();
    StringBuilder sb = new StringBuilder();
    //boolean ?set? 
    //private boolean ishead; setIshead
    //private boolean isHead; setHead
    //private boolean head; setHead
    if (clazz.equals(Boolean.class) || clazz.getName().equals("boolean")) {
        sb.append("set");
        if (name.startsWith("is")) {
            if (name.length() > 2) {
                //private boolean isHead; setHead
                if (Character.isUpperCase(name.charAt(2))) {
                    sb.append(name.substring(2));
                } else {//private boolean ishead; setIshead
                    sb.append(name.toUpperCase().charAt(0));
                    sb.append(name.substring(1));
                }
            } else {
                sb.append(name.toUpperCase().charAt(0));
                sb.append(name.substring(1));
            }
        } else {//private boolean head; setHead
            sb.append(name.toUpperCase().charAt(0));
            sb.append(name.substring(1));
        }
    } else {
        sb.append("set");
        sb.append(name.toUpperCase().charAt(0));
        sb.append(name.substring(1));
    }
    return sb.toString();
}

From source file:com.pinterest.deployservice.common.ChangeFeedJob.java

private static String getConfigChangeMessage(Object ori, Object cur) {
    if (ori.getClass() != cur.getClass())
        return null;

    List<String> results = new ArrayList<>();
    try {/*w w w  .j  a  v  a  2  s.c o  m*/
        if (ori instanceof List) {
            // Process list of custom object and others (e.g. List<String>)
            List<?> originalList = (List<?>) ori;
            List<?> currentList = (List<?>) cur;
            for (int i = 0; i < Math.max(originalList.size(), currentList.size()); i++) {
                Object originalItem = i < originalList.size() ? originalList.get(i) : null;
                Object currentItem = i < currentList.size() ? currentList.get(i) : null;
                if (!Objects.equals(originalItem, currentItem)) {
                    Object temp = originalItem != null ? originalItem : currentItem;
                    if (temp.getClass().getName().startsWith("com.pinterest")) {
                        results.add(String.format("%-40s  %-40s  %-40s%n", i,
                                toStringRepresentation(originalItem), toStringRepresentation(currentItem)));
                    } else {
                        results.add(String.format("%-40s  %-40s  %-40s%n", i, originalItem, currentItem));
                    }
                }
            }
        } else if (ori instanceof Map) {
            // Process Map (e.g. Map<String, String>)
            Map<?, ?> originalMap = (Map<?, ?>) ori;
            Map<?, ?> currentMap = (Map<?, ?>) cur;
            Set<String> keys = new HashSet<>();
            originalMap.keySet().stream().forEach(key -> keys.add((String) key));
            currentMap.keySet().stream().forEach(key -> keys.add((String) key));
            for (String key : keys) {
                Object originalItem = originalMap.get(key);
                Object currentItem = currentMap.get(key);
                if (!Objects.equals(originalItem, currentItem)) {
                    results.add(String.format("%-40s  %-40s  %-40s%n", key, originalItem, currentItem));
                }
            }
        } else {
            // Process other objects (e.g. custom object bean)
            Field[] fields = ori.getClass().getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object oriObj = field.get(ori);
                Object curObj = field.get(cur);
                if (!Objects.equals(oriObj, curObj)) {
                    if (oriObj instanceof List) {
                        results.add(String.format("%-40s  %-40s  %-40s%n", field.getName(),
                                toStringRepresentation(oriObj), toStringRepresentation(curObj)));
                    } else {
                        results.add(String.format("%-40s  %-40s  %-40s%n", field.getName(), oriObj, curObj));
                    }

                }
            }
        }
    } catch (Exception e) {
        LOG.error("Failed to get config message.", e);
    }

    if (results.isEmpty()) {
        return null;
    }

    StringBuilder resultBuilder = new StringBuilder();
    resultBuilder.append(String.format("%n%-40s  %-40s  %-40s%n", "Name", "Original Value", "Current Value"));
    results.stream().forEach(resultBuilder::append);
    return resultBuilder.toString();
}

From source file:com.ykun.commons.utils.excel.ExcelUtils.java

/**
 * xlsheaders/*  w  w  w .java 2 s.c om*/
 *
 * @param list    the list
 * @param headers the headers
 * @param out     the out
 */
public static <T> void export(List<T> list, List<String> headers, OutputStream out) {
    // ?
    if (list == null || list.size() == 0) {
        return;
    }

    try {
        Workbook workbook = new XSSFWorkbook(); // XSSFWorkbook
        Sheet sheet = workbook.createSheet(); // ?Sheet

        // ?
        int rowNo = 0;
        CellStyle headerStyle = createHeaderStyle(workbook);
        if (headers != null && headers.size() > 0) {
            Row row = sheet.createRow(rowNo++);
            for (int i = 0; i < headers.size(); i++) {
                Cell cell = row.createCell(i);
                cell.setCellStyle(headerStyle);
                cell.setCellValue(headers.get(i));
            }
        }

        // ?
        CellStyle normalStyle = createNormalStyle(workbook);
        for (T t : list) {
            Row row = sheet.createRow(rowNo++);
            Field[] fields = t.getClass().getDeclaredFields();
            int column = 0;
            for (int i = 0; i < fields.length; i++) {
                Object value;
                Field field = fields[i];
                ExcelField excelField = field.getAnnotation(ExcelField.class);
                if (excelField != null && !excelField.ignore()) {
                    String methodName = PREFIX_GETTER + StringUtils.capitalize(field.getName()); // get???getisEnable?
                    Method method = t.getClass().getMethod(methodName, new Class[] {});
                    value = method.invoke(t, new Object[] {});
                } else if (excelField != null && excelField.ignore()) {
                    continue;
                } else {
                    String methodName = PREFIX_GETTER + StringUtils.capitalize(field.getName()); // get???getisEnable?
                    Method method = t.getClass().getMethod(methodName, new Class[] {});
                    value = method.invoke(t, new Object[] {});
                }
                row.setRowStyle(normalStyle);
                addCell(row, column++, value, excelField);
            }
        }
        workbook.write(out);
    } catch (Exception e) {
        logger.error("Export error:", e);
        throw new RuntimeException(e);
    }
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static void printObjectProperties(final Logger log, final Object object,
        final boolean onlyImportantField) {
    Field[] fields = object.getClass().getDeclaredFields();
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String name = field.getName();
            if (!name.startsWith("this")) {
                Object value = null;
                try {
                    field.setAccessible(true);
                    value = field.get(object);
                    if (null == value) {
                        value = "";
                    }/*from  w  w  w  .  j ava2 s .  c  o m*/
                } catch (IllegalArgumentException e) {
                    System.out.println(e);
                } catch (IllegalAccessException e) {
                    System.out.println(e);
                }

                if (onlyImportantField) {
                    Annotation annotation = field.getAnnotation(ImportantField.class);
                    if (null == annotation) {
                        continue;
                    }
                }

                if (log != null) {
                    log.info(name + "=" + value);
                } else {
                    System.out.println(name + "=" + value);
                }
            }
        }
    }
}

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

/**
 *  (?),key fieldName,value .// ww w .j  av a2s.  c  om
 *
 * @param obj
 *            the obj
 * @param excludeFieldNames
 *            ?field names,?nullOrEmpty ?
 * @return the field value map
 * @see #getAllFieldList(Object, String[])
 * @see org.apache.commons.lang3.reflect.MemberUtils#setAccessibleWorkaround(AccessibleObject)
 */
public static Map<String, Object> getAllFieldNameAndValueMap(Object obj, String[] excludeFieldNames) {
    List<Field> fieldList = getAllFieldList(obj, excludeFieldNames);

    if (Validator.isNullOrEmpty(fieldList)) {
        return Collections.emptyMap();
    }
    Map<String, Object> map = new TreeMap<String, Object>();
    for (Field field : fieldList) {
        //XXX see org.apache.commons.lang3.reflect.MemberUtils.setAccessibleWorkaround(AccessibleObject)
        field.setAccessible(true);
        try {
            map.put(field.getName(), field.get(obj));
        } catch (Exception e) {
            LOGGER.error(e.getClass().getName(), e);
            throw new ReflectException(e);
        }
    }
    return map;
}

From source file:com.alibaba.jstorm.cluster.StormConfig.java

public static HashMap<String, Object> getClassFields(Class<?> cls)
        throws IllegalArgumentException, IllegalAccessException {
    Field[] list = cls.getDeclaredFields();
    HashMap<String, Object> rtn = new HashMap<String, Object>();
    for (Field f : list) {
        String name = f.getName();
        rtn.put(name, f.get(null).toString());

    }/*from  w w w.j  a v  a2  s  .  c  o m*/
    return rtn;
}

From source file:common.utils.ReflectionAssert.java

/**
 * All fields are checked for null values (except the static ones).
 * Private fields are also checked./* w  ww.j  ava 2  s.  c  o  m*/
 * This is NOT recursive, only the values of the first object will be checked.
 * An assertion error will be thrown when a property is null.
 * 
 * @param message    a message for when the assertion fails
 * @param object     the object that will be checked for null values.
 */
public static void assertPropertiesNotNull(String message, Object object) {
    Set<Field> fields = ReflectionUtils.getAllFields(object.getClass());
    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            String formattedMessage = formatMessage(message,
                    "Property '" + field.getName() + "' in object '" + object.toString() + "' is null ");
            assertNotNull(formattedMessage, ReflectionUtils.getFieldValue(object, field));
        }
    }

}

From source file:com.igormaznitsa.upom.UPomModel.java

private static Field findDeclaredFieldForName(final Class klazz, final String fieldName) {
    Field result = null;// w w  w. j a va2  s .co  m
    Class curr = klazz;
    while (curr.getName().startsWith(MAVEN_MODEL_PACKAGE_PREFIX)) {
        for (final Field m : curr.getDeclaredFields()) {
            if (m.getName().equalsIgnoreCase(fieldName)) {
                result = m;
                break;
            }
        }
        if (result != null) {
            result.setAccessible(true);
            break;
        }
        curr = klazz.getSuperclass();
    }
    return result;
}

From source file:Main.java

/**
 * Get the name of the field by looking at the XmlElement annotation.
 *
 * @param jaxbClass//from  w  ww .  j a  va2  s .c  om
 * @param fieldName
 * @return
 * @throws NoSuchFieldException
 */
private static QName getXmlElementRefOrElementQName(Class<?> jaxbClass, Field field)
        throws NoSuchFieldException {
    XmlElementRef xmlElementRef = (XmlElementRef) getAnnotation(field, XmlElementRef.class);
    if (xmlElementRef != null) {
        return new QName(xmlElementRef.namespace(), xmlElementRef.name());
    }
    XmlElement xmlElement = (XmlElement) getAnnotation(field, XmlElement.class);

    // If XmlElement does not exist, default to using the field name
    if (xmlElement == null || xmlElement.name().equals("##default")) {
        return new QName("", field.getName());
    }
    return new QName(xmlElement.namespace(), xmlElement.name());
}