Can beanutil get a property of one field with its native type

Hi: I use BeanUtil to get the properties of some bean and then put them on the map. However, I found that it getProperty()can only return a string value, I wonder if it can return its own (original) type?

For instance:

Bean:

public class Entity {
 private String  name;
 private int   age;
 private List<Date> childs = new ArrayList<Date>();

 public Entity(String name, int age, List<Date> childs) {
  this.name = name;
  this.age = age;
  this.childs = childs;
 }

 public static Entity newInstance() {
  List<Date> list = new ArrayList<Date>();
  list.add(new Date());
  list.add(new Date());
  return new Entity("Beanutil", 23, list);
 }
 //the getter and setter for all the fields
}

Then I want to get some field property of it,and I do not exactly know which fields are requried,so I use it this way:

public class BeanUtilMain {
 public static void main(String[] args){
  String[] requestPro={"name","childs"}; //this field is specified by clien
  Map<String, Object> map=new HashMap<String, Object>();
  Entity en=Entity.newInstance();
  for(String p:requestPro){
   map.put(p, BeanUtils.getProperty(en, p));
  }
  System.out.println(map);
 }
}

Then the mapping:

{name=beanutil, childs=Wed Dec 01 12:24:37 CST 2010}

The field type "childs" is java.util.List, but in this example it is converted to java.lang.String.

I need to save the type of orignal fields on the map.

Any ideas?

+3
source share
1 answer

You can use PropertyUtils.getProperty(Object, String)to accomplish just that. It returns the value of the field without type conversion.

+2

Source: https://habr.com/ru/post/1777840/


All Articles