Skip to content

Instantly share code, notes, and snippets.

@chrisport
Created Sep 8, 2014
Embed
What would you like to do?
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