- import java.beans.BeanInfo;
- import java.beans.IntrospectionException;
- import java.beans.Introspector;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.InvocationTargetException;
- import java.util.Date;
- import org.apache.commons.beanutils.BeanUtils;
- /**
- * @author Shawn
- *
- */
- class Heart{
- private String left;
- private String right;
- public String getLeft() {
- return left;
- }
- public void setLeft(String left) {
- this.left = left;
- }
- public String getRight() {
- return right;
- }
- public void setRight(String right) {
- this.right = right;
- }
-
- }
- class Person{
- private Heart heart;
- private Date birthday;
- public Date getBirthday() {
- return birthday;
- }
- public void setBirthday(Date birthday) {
- this.birthday = birthday;
- }
- public Heart getHeart() {
- return heart;
- }
- public void setHeart(Heart heart) {
- this.heart = heart;
- }
- }
- public class BeanUtilsTest2 {
- /**
- * @param args
- * @throws NoSuchMethodException
- * @throws InvocationTargetException
- * @throws IllegalAccessException
- */
- public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
- // TODO Auto-generated method stub
- Person p = new Person();
- BeanInfo beanInfo = null;
- try {
- beanInfo = Introspector.getBeanInfo(Person.class);
- } catch (IntrospectionException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- PropertyDescriptor[] pds = null;
- try {
- pds = beanInfo.getPropertyDescriptors();
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- for(PropertyDescriptor pd : pds){
- System.out.println(pd.getName());
- }
- // System.out.println(BeanUtils.getProperty(p, "heart"));
- }
- }
复制代码 打印结果:
birthday
class
heart
我这里实现了人和心脏的类,然后想通过BeanUtils的级联操作,设置heart属性,但是发现会报错,测试了一下,用内省打印了一下获取到的属性名,发现多了一个class,谁知道这个class哪里来的? |