You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何判断BeanWrapper PropertyDescriptor属性是否为静态,仅打印实例属性?

解决BeanWrapperImpl识别静态setter为属性的问题

你遇到的这个问题是因为Spring的BeanWrapperImpl在识别JavaBean属性时,只要方法符合setXxx/getXxx的命名规范,不管方法是不是静态的,都会把它当作对应的属性。所以静态的setThird方法被识别成了third属性,哪怕它没有对应的实例字段或getter。

要只保留实例属性,我们可以在遍历PropertyDescriptor的时候,过滤掉那些关联了静态方法的属性。具体做法是检查属性的readMethod和writeMethod是否为静态方法,如果是就排除掉。

修改后的代码

import java.lang.reflect.Modifier;
import org.springframework.beans.BeanWrapperImpl;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        var myObject = new MyObject();
        var wrapper = new BeanWrapperImpl(myObject);

        Stream.of(wrapper.getPropertyDescriptors())
              .filter(p -> {
                  // 检查该属性的getter或setter是否为静态方法
                  boolean hasStaticReadMethod = p.getReadMethod() != null && Modifier.isStatic(p.getReadMethod().getModifiers());
                  boolean hasStaticWriteMethod = p.getWriteMethod() != null && Modifier.isStatic(p.getWriteMethod().getModifiers());
                  // 只保留没有静态方法关联的属性
                  return !hasStaticReadMethod && !hasStaticWriteMethod;
              })
              .forEach(p -> {
                final String name = p.getName();
                final Object value =
                    wrapper.isReadableProperty(name)
                  ? wrapper.getPropertyValue(name) 
                  : "not readable";

                System.out.println(name + " = " + value);
              });
    }
}

class MyObject {
    private static String third = "i am static";

    public String getSecond(){return "abc";}
    public boolean getFirst(){return true;}

    // presence of this method affects availability of property "third"
    public static void setThird(String x){
      // nothing
    }
}

代码说明

  • 使用Modifier.isStatic()方法判断方法是否为静态:我们分别检查属性的读方法(getter)和写方法(setter),只要其中一个是静态的,就排除该属性。
  • 这样过滤后,third属性因为关联了静态的setThird方法,会被排除在外,最终输出只有实例属性first和second。

运行结果

first = true
second = abc

内容的提问来源于stack exchange,提问作者diziaq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 16:35:13