XStream private attributes in Java
How does XStream gets my object values since they are private?
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);
}
}
and how do i highlight and indent my code in stackoverflow?
How does XStream gets my object values since they are private?
It uses reflection. See the Converter listing for details on how XStream convers various java types
How do i highlight and indent my code in stackoverflow?
Highlight the text and press the code button that looks like 101010
I don't know XStream, but they sure use the reflection API where you can disable the accessors (public, private, ...).
With API reflection. You can get any field of a class with 'getDeclaredField' method, and then get the field's value
They do it by reflection. This way you can access even private members. For examples, look here.
精彩评论