Skip to content

Instantly share code, notes, and snippets.

@hackeris
Last active August 9, 2017 11:46
Show Gist options
  • Save hackeris/80791ca5a0772be5775333860343a5d1 to your computer and use it in GitHub Desktop.
Save hackeris/80791ca5a0772be5775333860343a5d1 to your computer and use it in GitHub Desktop.
import com.google.gson.Gson;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by hackeris on 16/9/16.
*/
public class JsonConvert {
private class SomeClass {
String someProperty;
}
interface SomeInterface {
SomeClass getAnObject();
List<SomeClass> getSomeObjects();
}
private static class RpcDemo {
private static Map<String, String> jsonPool = makeJsonPool();
private static Map<String, String> makeJsonPool() {
Map<String, String> pool = new HashMap<>();
pool.put("getAnObject", "{\"someProperty\":\"Some Value\"}");
pool.put("getSomeObjects", "[{\"someProperty\":\"Some Value 1\"},{\"someProperty\":\"Some Value 2\"}]");
return pool;
}
static <Interface> Interface refer(final Class<Interface> interfaceClass) {
return (Interface) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, ((proxy, method, args) -> {
String responseJson = jsonPool.get(method.getName());
return new Gson().fromJson(responseJson, method.getReturnType());
}));
}
}
public static void main(String[] args) {
SomeInterface service = RpcDemo.refer(SomeInterface.class);
SomeClass anObject = service.getAnObject();
System.out.println(anObject.someProperty);
List<SomeClass> someObjects = service.getSomeObjects();
System.out.println(someObjects.get(0).someProperty);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment