内省操作javabean属性
程序员文章站
2022-06-14 12:09:08
内省操作javabean属性,javabean person类。
public class person {
private string name;
private...
内省操作javabean属性,javabean person类。
public class person { private string name; private string password; private int age; public string getab(){ return null; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } public int getage() { return age; } public void setage(int age) { this.age = age; } }
内省操作
import java.beans.beaninfo; import java.beans.introspector; import java.beans.propertydescriptor; import java.lang.reflect.method; import org.junit.test; //使用内省api操作bean的属性 public class demo1 { // 得到bean的所有属性 @test public void test1() throws exception { beaninfo info = introspector.getbeaninfo(person.class, object.class); propertydescriptor[] pds = info.getpropertydescriptors(); for (propertydescriptor pd : pds) { system.out.println(pd.getname()); } } // 得到bean的指定属性:get @test public void test2() throws exception { person p = new person(); propertydescriptor pd = new propertydescriptor("age", person.class); // 得到属性的写方法,为属性赋值 method method = pd.getwritemethod(); // setage method.invoke(p, 45); // system.out.println(p.getage()); // 获取属性值 method = pd.getreadmethod(); system.out.println(method.invoke(p, null)); } //获取当前操作属性的类型 @test public void test3() throws exception { person p = new person(); propertydescriptor pd = new propertydescriptor("age", person.class); system.out.println(pd.getpropertytype()); } }