1package test.javassist.proxy;
2
3import junit.framework.TestCase;
4
5import java.io.FileInputStream;
6import java.io.FileOutputStream;
7import java.io.ObjectInputStream;
8import java.io.ObjectOutputStream;
9import java.io.Serializable;
10import java.lang.reflect.Method;
11
12import javassist.util.proxy.ProxyFactory;
13
14public class ProxySimpleTest extends TestCase {
15    public void testReadWrite() throws Exception {
16        final String fileName = "read-write.bin";
17        ProxyFactory.ClassLoaderProvider cp = ProxyFactory.classLoaderProvider;
18        ProxyFactory.classLoaderProvider = new ProxyFactory.ClassLoaderProvider() {
19            public ClassLoader get(ProxyFactory pf) {
20                return new javassist.Loader();
21            }
22        };
23        ProxyFactory pf = new ProxyFactory();
24        pf.setSuperclass(ReadWriteData.class);
25        Object data = pf.createClass().newInstance();
26        // Object data = new ReadWriteData();
27        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName));
28        oos.writeObject(data);
29        oos.close();
30        ProxyFactory.classLoaderProvider = cp;
31
32        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName));
33        Object data2 = ois.readObject();
34        ois.close();
35        int i = ((ReadWriteData)data2).foo();
36        assertEquals(4, i);
37    }
38
39    public static class ReadWriteData implements Serializable {
40        public int foo() { return 4; }
41    }
42
43    public void testWriteReplace() throws Exception {
44        ProxyFactory pf = new ProxyFactory();
45        pf.setSuperclass(WriteReplace.class);
46        Object data = pf.createClass().newInstance();
47        assertEquals(data, ((WriteReplace)data).writeReplace());
48
49        ProxyFactory pf2 = new ProxyFactory();
50        pf2.setSuperclass(WriteReplace2.class);
51        Object data2 = pf2.createClass().newInstance();
52        Method meth = data2.getClass().getDeclaredMethod("writeReplace", new Class[0]);
53        assertEquals("javassist.util.proxy.SerializedProxy",
54                    meth.invoke(data2, new Object[0]).getClass().getName());
55    }
56
57    public static class WriteReplace implements Serializable {
58        public Object writeReplace() { return this; }
59    }
60
61    public static class WriteReplace2 implements Serializable {
62        public Object writeReplace(int i) { return new Integer(i); }
63    }
64}
65