public static GenericType inferGenericTypeOnMapOrCollectionField(Field field) { Class owner = field.getDeclaringClass(); Type t = GenericTypeReflector.getExactFieldType(field, owner); if (Map.class.isAssignableFrom(field.getType())) { return inferMap(t); } else if (Collection.class.isAssignableFrom(field.getType())) { return inferCollection(t); } else { throw new IllegalArgumentException(String.format("field is type of %s, only Map or Collection field can be inferred", field.getType().getName())); } }
private static GenericType inferCollection(Type type) { CollectionGenericType ret = new CollectionGenericType(); Type valueType = GenericTypeReflector.getTypeParameter(type, Collection.class.getTypeParameters()[0]); ret.isInferred = valueType != null; if (valueType == null) { return ret; } ret.valueType = GenericTypeReflector.erase(valueType); if (Map.class.isAssignableFrom(ret.valueType)) { ret.nestedGenericValue = inferMap(valueType); } else if (Collection.class.isAssignableFrom(ret.valueType)) { ret.nestedGenericValue = inferCollection(valueType); } return ret; }
private static GenericType inferMap(Type type) { MapGenericType ret = new MapGenericType(); Type keyType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[0]); Type valueType = GenericTypeReflector.getTypeParameter(type, Map.class.getTypeParameters()[1]); ret.isInferred = keyType != null && valueType != null; if (keyType == null || valueType == null) { return ret; } ret.keyType = GenericTypeReflector.erase(keyType); ret.valueType = GenericTypeReflector.erase(valueType); if (!ret.isInferred) { return ret; } if (Map.class.isAssignableFrom(ret.keyType)) { ret.nestedGenericKey = inferMap(keyType); } else if (Collection.class.isAssignableFrom(ret.keyType)) { ret.nestedGenericKey = inferCollection(keyType); } if (Map.class.isAssignableFrom(ret.valueType)) { ret.nestedGenericValue = inferMap(valueType); } else if (Collection.class.isAssignableFrom(ret.valueType)) { ret.nestedGenericValue = inferCollection(valueType); } return ret; }