[Turn] Java for specific types of generic T

In the daily development especially when the frame design or utility reflection, often like to do something practical class, but due to the abstract system and other issues, often generics do something practical. So how to get a specific class like it in generics?

Solution: The parent class itself does not acquire particular generic type, only an abstract method to provide a specific type of the subclass

public abstract class Foo<T> {  
    public abstract Class getEntityClass();  
}  

public class Child extends Foo<String> {  
    public Class getEntityClass() {  
        return String.class;  
    }  
}  

Tools:

mport java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class GenericsUtils {
    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends
     * GenricManager<Book>
     * 
     * @param clazz The class to introspect
     * @return the first generic declaration, or <code>Object.class</code> if cannot be determined
     */
    public static Class getSuperClassGenricType(Class clazz) {
        return getSuperClassGenricType(clazz, 0);
    }

    /**
     * 通过反射,获得定义Class时声明的父类的范型参数的类型. 如public BookManager extends GenricManager<Book>
     * 
     * @param clazz clazz The class to introspect
     * @param index the Index of the generic ddeclaration,start from 0.
     */
    public static Class getSuperClassGenricType(Class clazz, int index)
            throws IndexOutOfBoundsException {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            return Object.class;
        }
        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if (index >= params.length || index < 0) {
            return Object.class;
        }
        if (!(params[index] instanceof Class)) {
            return Object.class;
        }
        return (Class) params[index];
    }
}

 

Published 225 original articles · won praise 105 · views 530 000 +

Guess you like

Origin blog.csdn.net/chenpeng19910926/article/details/104028317