Java Beans, BeanUtils, and the Boolean wrapper class

前端 未结 3 1100
情深已故
情深已故 2021-01-01 19:42

I\'m using BeanUtils to manipulate Java objects created via JAXB, and I\'ve run into an interesting issue. Sometimes, JAXB will create a Java object like this:



        
3条回答
  •  孤街浪徒
    2021-01-01 20:01

    Workaround to handle Boolean isFooBar() case with BeanUtils

    1. Create new BeanIntrospector

    private static class BooleanIntrospector implements BeanIntrospector{
        @Override
        public void introspect(IntrospectionContext icontext) throws IntrospectionException {
            for (Method m : icontext.getTargetClass().getMethods()) {
                if (m.getName().startsWith("is") && Boolean.class.equals(m.getReturnType())) {
                    String propertyName = getPropertyName(m);
                    PropertyDescriptor pd = icontext.getPropertyDescriptor(propertyName);
    
                    if (pd == null)
                        icontext.addPropertyDescriptor(new PropertyDescriptor(propertyName, m, getWriteMethod(icontext.getTargetClass(), propertyName)));
                    else if (pd.getReadMethod() == null)
                        pd.setReadMethod(m);
    
                }
            }
        }
    
        private String getPropertyName(Method m){
            return WordUtils.uncapitalize(m.getName().substring(2, m.getName().length()));
        }
    
        private Method getWriteMethod(Class clazz, String propertyName){
            try {
                return clazz.getMethod("get" + WordUtils.capitalize(propertyName));
            } catch (NoSuchMethodException e) {
                return null;
            }
        }
    }
    

    1. Register BooleanIntrospector:

      BeanUtilsBean.getInstance().getPropertyUtils().addBeanIntrospector(new BooleanIntrospector());

提交回复
热议问题