1

XStream 如何获取我的对象值,因为它们是私有的?

import com.thoughtworks.xstream.XStream;

class Person {
    private String name;

    public Person(String n) {
        name = n;
    }
}

public class Main {
    public static void main(String[] args) {
        XStream stream = new XStream();

        Person p = new Person("Joe");
        String xml = stream.toXML(p);
        System.out.println(xml);
    }
}

以及如何在stackoverflow中突出显示和缩进我的代码?

4

4 回答 4

1

我不知道 XStream,但他们确实使用了反射 API,您可以在其中禁用访问器(公共、私有......)。

于 2010-01-29T18:10:21.583 回答
1

XStream 如何获取我的对象值,因为它们是私有的?

它使用反射。有关XStream 如何转换各种 java 类型的详细信息,请参阅转换器列表

如何在stackoverflow中突出显示和缩进我的代码?

突出显示文本并按下看起来像 101010 的代码按钮

于 2010-01-29T18:11:14.623 回答
1

With API reflection. You can get any field of a class with 'getDeclaredField' method, and then get the field's value

于 2010-01-29T18:22:26.800 回答
0

他们通过反思来做到这一点。这样您甚至可以访问私人成员。例如,看这里

于 2010-01-29T18:11:05.340 回答