Skip to content

Instantly share code, notes, and snippets.

@chrisport
Created September 8, 2014 20:07
Show Gist options
  • Save chrisport/c2780eff8fa234087751 to your computer and use it in GitHub Desktop.
Save chrisport/c2780eff8fa234087751 to your computer and use it in GitHub Desktop.
public class PojoProxy implements InvocationHandler {
private Map<String, Object> map;
private Map<String, List<Observer>> observers = new HashMap<String, List<Observer>>();
public static Object newInstance(Class[] interfaces, Context context) {
return Proxy.newProxyInstance(context.getClassLoader(),
interfaces,
new PojoProxy(new HashMap()));
}
public PojoProxy(Map map) {
this.map = map;
}
public Object invoke(Object proxy, Method m, Object[] args) throws
Throwable {
String methodName = m.getName();
if (methodName.startsWith("get")) {
String name = methodName.substring(methodName.indexOf("get") + 3).toLowerCase();
return map.get(name);
} else if (methodName.startsWith("set")) {
String name = methodName.substring(methodName.indexOf("set") + 3).toLowerCase();
map.put(name, args[0]);
notifyObservers(name, args[0]);
return null;
} else if (methodName.startsWith("is")) {
String name = methodName.substring(methodName.indexOf("is") + 2).toLowerCase();
return (map.get(name));
} else if (methodName.equals("addObserver")) {
addObserver((String) args[0], (Observer) args[1]);
}
return null;
}
private void addObserver(String field, Observer observer) {
List<Observer> list = observers.get(field.toLowerCase());
if (list == null) {
list = new LinkedList<Observer>();
observers.put(field.toLowerCase(), list);
}
list.add(observer);
}
private void notifyObservers(String field, final Object value) {
synchronized (observers) {
final List<Observer> list = observers.get(field.toLowerCase());
if (list == null) {
return;
}
for (final Observer observer : list) {
if (Config.SIMULATION_MODE == Simulation.ON_UI_THREAD) {
observer.update(value);
} else {
UIHandler.instance.post(new Runnable() {
@Override
public void run() {
observer.update(value);
}
});
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment