Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @SuppressWarnings("unchecked")
- public Class<T> getValueType() {
- for (Class<?> clazz = getClass(); clazz.getSuperclass() != null; clazz = clazz.getSuperclass()) {
- Type genericSuperclass = clazz.getGenericSuperclass();
- if (genericSuperclass instanceof ParameterizedType) {
- Type[] typeArguments = ((ParameterizedType)genericSuperclass).getActualTypeArguments();
- if (typeArguments.length > 0) {
- // we are looking for first type argument
- Type type = typeArguments[0];
- try {
- if (type instanceof ParameterizedType) {
- // type argument is parameterized type, we have to get raw type
- return (Class<T>)((ParameterizedType)type).getRawType();
- }
- else if (type instanceof GenericArrayType) {
- // type argument is array type, we have to analyze generic component
- Type componentType = ((GenericArrayType)type).getGenericComponentType();
- // analyze the dimensions
- StringBuilder sb = new StringBuilder();
- sb.append('[');
- while (componentType instanceof GenericArrayType) {
- sb.append('[');
- componentType = ((GenericArrayType)componentType).getGenericComponentType();
- }
- // analyze the component class
- Class<?> componentClass = null;
- if (componentType instanceof ParameterizedType) {
- componentClass = (Class<?>)((ParameterizedType)componentType).getRawType();
- }
- else {
- componentClass = (Class<?>)componentType;
- }
- // finish the class name
- if (componentClass.isPrimitive()) {
- sb.append(PrimitiveUtils.abbreviate(componentClass));
- }
- else {
- sb.append('L').append(componentClass.getName()).append(';');
- }
- // find the class
- return (Class<T>)Class.forName(sb.toString());
- }
- else if (type instanceof TypeVariable) {
- // type argument is type variable, we will return first bound
- Type[] bounds = ((TypeVariable<?>)type).getBounds();
- if (bounds.length > 0) {
- if (bounds[0] instanceof ParameterizedType) {
- return (Class<T>)((ParameterizedType)bounds[0]).getRawType();
- }
- else {
- return (Class<T>)bounds[0];
- }
- }
- }
- else {
- return (Class<T>)type;
- }
- }
- catch (ClassCastException exc) {
- // only for catching
- }
- catch (ClassNotFoundException exc) {
- // only for catching
- }
- }
- }
- }
- return (Class<T>)Object.class;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement