BeanUtils不适用于链设置器 [英] BeanUtils not works for chain setter

查看:445
本文介绍了BeanUtils不适用于链设置器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

class tester
{
    @Test
    public void testBeanUtils() throws InvocationTargetException, IllegalAccessException, NoSuchMethodException
    {
        Stranger stranger = new Stranger();
        BeanUtils.setProperty(stranger,"name","wener");
        BeanUtils.setProperty(stranger,"xname","xwener");
        BeanUtils.setProperty(stranger,"yname","ywener");

        System.out.println(stranger);
    }
    @Data// lombok annotation generate all setter and getter
    public static class Stranger
    {
        @Accessors(chain = true)// generate chained setter
        String name;
        String xname;
        String yname;

        public Stranger setYname(String yname)// no lombok, still not work
        {
            this.yname = yname;
            return this;
        }
    }
}

我的输出:

TestValues.Stranger(name=null, xname=xwener, yname=null)

这有什么问题?连锁二传手是一件好事。
是否建议?

What's wrong with this? chain setter is a good thing. Any suggests ?

编辑

再次回到此问题。这次我无法删除 Accessors链
现在,我使用 commons-lang3 来实现。

Back to this problem again.This time I can not remove the Accessors chain. Now, I use the commons-lang3 to achieve.

// force access = true is required
Field field = FieldUtils.getField(bean.getClass(), attrName, true);
field.set(bean,value);

对于那些遇到同样问题的人。

For those who got the same problem.

推荐答案

这很简单: BeanUtils 相当奇怪, Introspector 它使用:

That's simple: BeanUtils are rather strange and so is Introspector it uses:

虽然 BeanUtils.setProperty 声明了一些异常,似乎默默地忽略不存在要设置的属性。最终的罪魁祸首是 Introspector ,只需需要 setter的无效性。

Although BeanUtils.setProperty declares some exceptions, it seems to silently ignore the non-existence of the property to be set. The ultimate culprit is the Introspector which simply requires the voidness of setter.

我称之为被设计打破,但是YMMV。它是一个古老的类,在那些黑暗时代还没有发明流畅的界面。使用 访问者(chain = false) 禁用链接。

I'd call it broken by design, but YMMV. It's an old class and fluent interfaces weren't invented yet in those dark times. Use Accessors(chain=false) to disable chaining.

更重要的是:使用来源。得到它并获得一个调试器(它已经在您的IDE中)自己找到它(仍然可以随意询问它是否不起作用,只是尝试一下)。

More important: Use the source. Get it and get a debugger (it's already in your IDE) to find it out yourself (still feel free to ask if it doesn't work, just try a bit harder).

这篇关于BeanUtils不适用于链设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆