java反射

来源:互联网 发布:淘宝店铺身份复核逾期 编辑:程序博客网 时间:2024/06/05 05:04

啥也不说,直接先上代码:

 

        try        {            BeanInfo beanInfo = Introspector.getBeanInfo(newSubscriberInfo.getClass());                        for (PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors())            {                if ("name".equalsIgnoreCase(propertyDescriptor.getName()))                {                    propertyDescriptor.getWriteMethod()                            .invoke(newSubscriberInfo, "chenxiaoming");                }                if ("id".equals(propertyDescriptor.getName()))                {                    propertyDescriptor.getWriteMethod()                            .invoke(newSubscriberInfo, "27");                }                if ("account".equals(propertyDescriptor.getName()))                {                    propertyDescriptor.getWriteMethod()                            .invoke(newSubscriberInfo, 1);                }            }        }        catch (Exception e)        {            e.printStackTrace();        }

 

 

通过反射将类中的属性设值,咋一看这个方法不过如此,或许还没有直接设值来的直接,但是仔细一想这个方法,用处还是很特别的:

举个例子,比如毫不相关的类,同时需要在新增了一个字段:name,而这个字段的值的来源又是一样的,如果不是使用上述思路的话,可能使用这个类的地方都需要加下设值,不同的类可能需要改动的地方很多,如果使用这个方法,在共同的地方,增加反射设值,只要有该字段的都可以设值。