gpt4 book ai didi

java - beanutil 可以使用其 native 类型获取一个字段的属性吗

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:39:34 26 4
gpt4 key购买 nike

嗨:我正在使用 BeanUtil 获取一些 bean 的属性,然后将它们映射到 map 上。但是我发现 getProperty() 只能返回字符串值,不知道它是否可以返回原生(原始)类型?

例如:

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);
}
}

那么 map 是:

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

“childs”字段的类型是java.util.List,但在示例中,它被转换为java.lang.String。

我必须保留 map 中字段的原始类型。

有什么想法吗?

最佳答案

您可以使用 PropertyUtils.getProperty(Object, String)来完成这个。它返回没有类型转换的字段值。

关于java - beanutil 可以使用其 native 类型获取一个字段的属性吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4321283/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com