1 package com.fasterxml.jackson.databind.interop; 2 3 import java.lang.reflect.*; 4 5 import com.fasterxml.jackson.databind.*; 6 7 // mostly for [Issue#57] 8 public class TestJDKProxy extends BaseMapTest 9 { 10 final ObjectMapper MAPPER = new ObjectMapper(); 11 12 public interface IPlanet { getName()13 String getName(); setName(String s)14 String setName(String s); 15 } 16 17 // bit silly example; usually wouldn't implement interface (no need to proxy if it did) 18 static class Planet implements IPlanet { 19 private String name; 20 Planet()21 public Planet() { } Planet(String s)22 public Planet(String s) { name = s; } 23 24 @Override getName()25 public String getName(){return name;} 26 @Override setName(String iName)27 public String setName(String iName) {name = iName; 28 return name; 29 } 30 } 31 32 /* 33 /******************************************************** 34 /* Test methods 35 /******************************************************** 36 */ 37 testSimple()38 public void testSimple() throws Exception 39 { 40 IPlanet input = getProxy(IPlanet.class, new Planet("Foo")); 41 String json = MAPPER.writeValueAsString(input); 42 assertEquals("{\"name\":\"Foo\"}", json); 43 44 // and just for good measure 45 Planet output = MAPPER.readValue(json, Planet.class); 46 assertEquals("Foo", output.getName()); 47 } 48 49 /* 50 /******************************************************** 51 /* Helper methods 52 /******************************************************** 53 */ 54 getProxy(Class<T> type, Object obj)55 public static <T> T getProxy(Class<T> type, Object obj) { 56 class ProxyUtil implements InvocationHandler { 57 Object _obj; 58 public ProxyUtil(Object o) { 59 _obj = o; 60 } 61 @Override 62 public Object invoke(Object proxy, Method m, Object[] args) throws Throwable { 63 Object result = null; 64 result = m.invoke(_obj, args); 65 return result; 66 } 67 } 68 @SuppressWarnings("unchecked") 69 T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class[] { type }, 70 new ProxyUtil(obj)); 71 return proxy; 72 } 73 } 74