Skip to content

Instantly share code, notes, and snippets.

@flowersinthesand
Created January 18, 2014 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save flowersinthesand/8486640 to your computer and use it in GitHub Desktop.
Save flowersinthesand/8486640 to your computer and use it in GitHub Desktop.
Data type conversion example for Portal for Java with Jackson
public abstract class Handler<T> implements Action<Map<String, Object>> {
private final Class<T> desiredType;
@SuppressWarnings("unchecked")
public Handler() {
// Each casting is not safe. Improve if you want to use in production
// See org.springframework.core.GenericTypeResolver.resolveTypeArgument
ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
desiredType = (Class<T>) pt.getActualTypeArguments()[0];
}
@Override
public void on(Map<String, Object> map) {
// The convertValue will convert map to JSON and JSON to desired type of object
// Reflection lib like Apache Commons BeanUtils may be better in performance
handle(new ObjectMapper().convertValue(map, desiredType));
}
public abstract void handle(T t);
}
socket.on(new Handler<Book>() {
@Override
public void handle(Book book) {
// Your logic here
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment