bean对象如何变成普通对象
时间: 2023-05-21 11:05:28 浏览: 107
Bean对象可以通过Java反射机制中的getDeclaredFields()方法获取其成员变量,进而通过该成员变量的get()方法获取成员变量的值,最终将Bean对象转换为普通对象。以下是示例代码:
```java
public class BeanToObjUtil {
/**
* 将Bean对象转换为普通的Java对象
*
* @param bean Bean对象
* @param clazz 对应的类对象
* @return 对应的普通Java对象
*/
public static Object beanToObj(Object bean, Class<?> clazz) {
Object obj = null;
try {
obj = clazz.newInstance();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
field.set(obj, field.get(bean));
}
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}
```
调用示例:
```java
//定义一个Java Bean对象
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//测试代码
public static void main(String[] args) {
//创建一个Person Bean对象
Person person = new Person("张三", 18);
//将Bean对象转换为普通Java对象
Object personObj = beanToObj(person, Person.class);
//验证转换结果
if(personObj instanceof Person){
Person p = (Person) personObj;
System.out.println(p.getName() + "," + p.getAge());
}
}
```
输出结果为:张三,18
阅读全文