Java內省(Introspector)

1、

    public static void main(String[] args) throws Exception {
        ReflectPoint pt1 = new ReflectPoint(3, 5);
        String propertyName = "x";

        PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());
        Method methodGetX = pd.getReadMethod();
        Object retVal = methodGetX.invoke(pt1);
        System.out.println(retVal);

        Method methodSetX = pd.getWriteMethod();
        methodSetX.invoke(pt1, 9);
        System.out.println(pt1.getX());
    }

運行結果:

3

9

2、

    public static void main(String[] args) throws Exception {
        ReflectPoint pt1 = new ReflectPoint(3, 5);
        String propertyName = "x";
        Object retVal = getProperty(pt1, propertyName);
        System.out.println(retVal);
    }

    private static Object getProperty(Object pt1, String propertyName)
            throws IntrospectionException, IllegalAccessException,
            InvocationTargetException {
		/*PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
		Method methodGetX = pd.getReadMethod();
		Object retVal = methodGetX.invoke(pt1);*/

        BeanInfo beanInfo = Introspector.getBeanInfo(pt1.getClass());
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        Object retVal = null;
        for (PropertyDescriptor pd : pds) {
            if (pd.getName().equals(propertyName)) {
                Method methodGetX = pd.getReadMethod();
                retVal = methodGetX.invoke(pt1);
                break;
            }
        }
        return retVal;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章