黑马程序员技术交流社区
标题:
内省对javaBean操作发现一个问题
[打印本页]
作者:
murder_fol
时间:
2013-10-18 22:02
标题:
内省对javaBean操作发现一个问题
本帖最后由 murder_fol 于 2013-10-19 15:53 编辑
import java.beans.*;
class Test
{
private int age;
private String name;
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name=name;
}
}
class IntrospectorDemo
{
public static void main(String[] args) throws Exception
{
Test t = new Test();
BeanInfo bi = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor [] pds = bi.getPropertyDescriptors();
System.out.println(pds.length);
for(PropertyDescriptor pd :pds)
{
String name = pd.getName();
String type =pd.getPropertyType().getName();
System.out.println(type);
System.out.println(name);
}
}
}
复制代码
今天写这个代码,无意中发现,只有两个bean属性,结果得到的pds中却有三个,另外一个是java.lang.Class 名字是class。不知道大家发现没有,
getPropertyDescriptor为什么要返回java.lang.Class呢?有什么用途吗?
作者:
fengche
时间:
2013-10-19 14:12
getPropertyDescriptor方法获取属性是根据该类的get方法 而不是看你定义了哪些属性,IntrospectorDemo类从Object中继承了getClass方法,所以会获得class属性
如下代码也能得到相同的结果
import java.beans.*;
class Test
{
public int getAge()
{
return 12;
}
public String getName()
{
return "张三";
}
}
public class IntrospectorDemo
{
public static void main(String[] args) throws Exception
{
Test t = new Test();
BeanInfo bi = Introspector.getBeanInfo(t.getClass());
PropertyDescriptor [] pds = bi.getPropertyDescriptors();
System.out.println(pds.length);
for(PropertyDescriptor pd :pds)
{
String name = pd.getName();
String type =pd.getPropertyType().getName();
System.out.println(type);
System.out.println(name);
}
}
}
复制代码
作者:
murder_fol
时间:
2013-10-19 15:52
谢谢 恍然大悟
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2