抽象父类获取子类的泛型 或接口泛型

jie通过getClass().getGenericSuperclass()或者子类的泛型

getClass().getGenericInterfaces();获取多个接口的泛型

GenericTypeResolver.resolveTypeArgument(GenericityService.class, GenericitySuper.class)

抽象父类

public abstract class GenericitySuper {
	
	protected Class getGenericity(){
		return (Class)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
	}
	protected List> getInterfaceGenericity(){
		List> list = new ArrayList>();
	    Type[] types = getClass().getGenericInterfaces();
	    for(Type type:types) {
	    	list.add((Class)((ParameterizedType)type).getActualTypeArguments()[0]);
	    }
		return list;
	}
}

接口

public interface GenericityInterface {

}
public interface Genericity2Interface {

}

子类

public class GenericityService extends GenericitySuper implements GenericityInterface,Genericity2Interface{
	
	public static void main(String[] args) {
		GenericityService service = new GenericityService();
		System.out.println(service.getGenericity().getSimpleName());
		for(Class cls:service.getInterfaceGenericity()) {
			System.out.println(cls.getSimpleName());
		}
	}

}

你可能感兴趣的:(java,泛型)