Java by API/java.beans/XMLEncoder — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
Admin (обсуждение | вклад) м (1 версия) |
(нет различий)
|
Текущая версия на 14:33, 31 мая 2010
Encoder: setPersistenceDelegate(Class<?> type, PersistenceDelegate persistenceDelegate)
import java.beans.DefaultPersistenceDelegate;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass(123);
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
String[] propertyNames = new String[] { "prop" };
encoder.setPersistenceDelegate(MyClass.class,
new DefaultPersistenceDelegate(propertyNames));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
int prop;
public MyClass(int prop) {
this.prop = prop;
}
public int getProp() {
return prop;
}
}
new XMLEncoder(OutputStream out)
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import javax.swing.JFrame;
public class Main {
public static void main(String args[]) {
JFrame x = new JFrame("Look at me");
x.setSize(200, 300);
x.setVisible(true);
x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FileOutputStream f;
try {
f = new FileOutputStream("Test.xml");
XMLEncoder e = new XMLEncoder(new BufferedOutputStream(f));
e.writeObject(x);
e.close();
} catch (Exception e) {
}
}
}
XMLEncoder: writeObject(Object o)
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
public class Main {
public static void main(String[] argv) throws Exception {
MyClass o = new MyClass();
o.setProp(1);
o.setProps(new int[] { 1, 2, 3 });
XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
new FileOutputStream("outfilename.xml")));
encoder.writeObject(o);
encoder.close();
}
}
class MyClass {
int i;
public int getProp() {
return i;
}
public void setProp(int i) {
this.i = i;
}
int[] iarray = new int[0];
public int[] getProps() {
return iarray;
}
public void setProps(int[] iarray) {
this.iarray = iarray;
}
static {
try {
BeanInfo info = Introspector.getBeanInfo(MyClass.class);
PropertyDescriptor[] propertyDescriptors = info.getPropertyDescriptors();
for (int i = 0; i < propertyDescriptors.length; ++i) {
PropertyDescriptor pd = propertyDescriptors[i];
if (pd.getName().equals("props")) {
pd.setValue("transient", Boolean.TRUE);
}
}
} catch (IntrospectionException e) {
}
}
}