如何像豆一样处理POJO? [英] How can I handle a POJO like a bean?

查看:77
本文介绍了如何像豆一样处理POJO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将简单的Java对象作为Bean访问?

How can I access a simple java object as a bean?

例如:

class Simple {
    private String foo;
    String getFoo() {
        return foo;
    }
    private void setFoo( String foo ) {
        this.foo = foo;
    }
}

现在我要像这样使用该对象:

Now I want to use this object like this:

Simple simple = new Simple();
simple.setFoo( "hello" );

checkSettings( simple );

所以我正在寻找方法checkSettings( Object obj )的实现:

So I'm looking for the implementation of the method checkSettings( Object obj ):

public boolean checkSettings( Object obj ) {
    // pseudocode here
    Bean bean = new Bean( obj );
    if( "hello".equals( bean.getAttribute( "foo" ) ) {
        return true;
    }
    return false;
}

Java语言包含一个名为java.beans的软件包,听起来像它可以为我提供帮助.但是我找不到一个好的起点.

The java language contains a package called java.beans which sounds like it could help me. But I don't find a good starting point.

有任何提示吗?

推荐答案

java.beans.Introspector.getBeanInfo 产生一个实现

java.beans.Introspector.getBeanInfo yields an object implementing java.beans.BeanInfo, which in turn can be used to get PropertyDescriptors and MethodDescriptors (via its getPropertyDescriptors- and getMethodDescriptors-methods), which in turn can be used to get the information you actually want.

与使用反射相比,这并不是真正的努力.

It is not really less effort than using reflection.

这篇关于如何像豆一样处理POJO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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