aboutsummaryrefslogtreecommitdiffstats
path: root/src/test/javassist/proxyfactory/Tester.java
blob: 601076da8152090ff29918420a2d15026d9e3099 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package javassist.proxyfactory;

import junit.framework.*;
import javassist.util.proxy.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.lang.reflect.Method;

class Hand implements java.io.Serializable {
    public int setHandler(int i) { return i; }
    int getHandler() { return 3; }
}

public class Tester extends TestCase {
    static class MHandler implements MethodHandler, java.io.Serializable {
        public Object invoke(Object self, Method m, Method proceed,
                             Object[] args) throws Throwable {
            System.out.println("Name: " + m.getName());
            return proceed.invoke(self, args);
        }
    }

    static MethodHandler mi = new MHandler();

    public void test() throws Exception {
        ProxyFactory f = new ProxyFactory();
        f.setSuperclass(Hand.class);
        Class c = f.createClass();
        Hand foo = (Hand)c.getConstructor().newInstance();
        ((Proxy)foo).setHandler(mi);
        assertTrue(ProxyFactory.isProxyClass(c));
        assertEquals(3, foo.getHandler());
    }

    public void test2() throws Exception {
        ProxyFactory f = new ProxyFactory();
        f.setSuperclass(Hand.class);
        Hand h = (Hand)f.create(new Class[0], new Object[0], mi);
        assertEquals(3, h.getHandler());

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ProxyObjectOutputStream out = new ProxyObjectOutputStream(bos);
        out.writeObject(h);
        out.close();
        byte[] bytes = bos.toByteArray();
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ProxyObjectInputStream in = new ProxyObjectInputStream(bis);
        Hand h2 = (Hand)in.readObject();
        assertEquals(3, h2.getHandler());
    }
}