在Bean类中设置数据

时间:2013-11-22 14:51:56

标签: java reflection

我陷入了一次手术。我有2个POJO Bean类

class A{
    private String name;

    public String getName(){
        return name;
    }

    public void setName(String name){
        this.name = name;
    }
}

............................................... ...................

class B {
    private String company;
    private Object object;

    public String getCompany() {
        return company;
    }

    public void setCompany(String company) {
        this.company = company;
    }

    public String getObject() {
        return object;
    }

    public void setObject(String object) {
        this.object = object;
    }

}

............................................... ...........

class SampleTest {
    public static void main(String[] args) {
        A a = new A();
        a.setName("Some Data");

        B b = new B();
        b.setCompany("Stack Overflow");
        b.setObject(a);

        //...... Next Lines.....
    }
}

有没有办法通过读取任何属性文件在B pojo类中设置数据?

示例属性文件:

#Property File<br>
B.company = Stack Overflow<br>
B.object.name = Some Data

请帮忙。 谢谢

1 个答案:

答案 0 :(得分:0)

一种方法可以是:

Properties prop = new Properties();
try
{
    // load a properties file
    prop.load(new FileReader("config.properties"));

    // get the property value
    B b = new B();
    b.setCompany(prop.getProperty("B.company"));

}
catch (IOException ex)
{
    ex.printStackTrace();
}