package com.spring.tools;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import org.junit.Test;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.BeanUtils;
public class BeanUtilsTest {
/**
* 实例化
*/
@Test
public void testInstantiate() {
//通过无参数构造函数实例化
Object obj = BeanUtils.instantiate(Person.class);
//Object obj = BeanUtils.instantiateClass(Person.class); //与BeanUtils.instantiate(Person.class)一样
if(obj instanceof Person) {
System.out.println(((Person) obj).getName());
}
//通过有参数构造函数实例化
Object obj2;
try {
obj2 = BeanUtils.instantiateClass(Person.class.getDeclaredConstructor(String.class), "a");
if(obj2 instanceof Person) {
System.out.println(((Person) obj2).getName());
}
} catch (BeanInstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 查找方法
* @throws Exception
*/
@Test
public void testFindDeclaredMethod() throws Exception {
User user = new User();
user.setCode("1");
user.setName("suncht");
//在所有方法中查找
Method method1 = BeanUtils.findDeclaredMethod(User.class, "getCode");
Object code1 = method1.invoke(user);
System.out.println(code1);
//在公共方法中查找
Method method2 = BeanUtils.findMethod(User.class, "getName");
Object code2 = method2.invoke(user);
System.out.println(code2);
}
/**
* 查找属性
* @throws Exception
*/
@Test
public void testPropertyDescriptor() throws Exception {
User user = new User();
user.setCode("222");
user.setName("suncht");
//获取属性
PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(User.class, "code");
//获取属性的get方法
Method getMethod = pd.getReadMethod();
Object code1 = getMethod.invoke(user);
System.out.println(code1);
//获取属性的get方法
Method setMethod = pd.getWriteMethod();
setMethod.invoke(user, "333");
System.out.println(user.getCode());
//根据方法查找属性
Method getCodeMethod = BeanUtils.findDeclaredMethod(User.class, "getCode2");
PropertyDescriptor pd2 = BeanUtils.findPropertyForMethod(getCodeMethod);
System.out.println(pd2);
}
public static class Person {
private String name = "aa";
public Person() {
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public static class User extends Person {
private String code;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
private String getCode2() {
return code;
}
}
}
复用代码系列:Spring的BeanUtils操作
最新推荐文章于 2024-07-11 16:56:49 发布