Java反射调用get/set方法,你还在这样用?

之前有些场景下碰到需要用到反射调用JavaBean的get/set方法时都是像以下这种拼接的方式来实现方法的调用。

        Article article = new Article();
        article.setTitle("这是标题");
        article.setPublishTime(LocalDateTime.now());
        Class<? extends Article> aClass = article.getClass();
        Field[] declaredFields = aClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            String name = declaredField.getName();
            String getMethodName = "get" + name.substring(0, 1).toUpperCase(Locale.ROOT) + name.substring(1);
            try {
                Method method = aClass.getMethod(getMethodName);
                Object invoke = method.invoke(article);
                System.out.println(name + "=" + invoke);
            } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
                e.printStackTrace();
            }
        }

发现上面这种方式只能拿到当前类的属性,想要拿父类的属性还得自己写循环实现。
image

今天发现一个类Introspector可以获取一个BeanInfo,然后从BeanInfo上获取属性描述符PropertyDescriptor,然后就可以遍历调用其中的readMethodwriteMethod方法来实现对JavaBean的get/set方法调用,具体代码如下。

try {
            BeanInfo beanInfo = Introspector.getBeanInfo(article.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
            Arrays.stream(propertyDescriptors)
                    .filter(p -> !"class".equals(p.getName()))
                    .forEach(pd -> {
                        try {
                            Method readMethod = pd.getReadMethod();
                            Object invoke = readMethod.invoke(article);
                            System.out.println(pd.getName() + "=" + invoke);
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IntrospectionException e) {
            e.printStackTrace();
        }

这种方式还会自动把父类的属性也会列出来。如果将上面的filter拿掉会发现多了一个class属性,所以平常使用的时候需要过滤掉class属性。
image

posted @ 2022-12-21 11:16  我叫乐多你养我啊  阅读(1318)  评论(0编辑  收藏  举报