public abstract class AnnotionMapper<T> implements Comparable<AnnotionMapper<T>>{ private Type _type; public AnnotionMapper() { Type superClass = getClass().getGenericSuperclass();// Get the direct superclass of the class _type = ((ParameterizedType) superClass).getActualTypeArguments()[0]; } public Type get_type() { return _type; } public void set_type(Type _type) { this._type = _type; } @Override public int compareTo(AnnotionMapper<T> o) { return 0; } public static void main(String[] args) { AnnotionMapper<ImageUrl> annotionMapper = new AnnotionMapper<ImageUrl>() { }; //AnnotionMapper<ImageUrl> annotionMapper = new AnnotionMapper<ImageUrl>(); System.out.println(annotionMapper.get_type()); /*new TypeReference<T>() { };*/ }
This code is weird. If you add the abstract keyword to the class, that is, the new in the main method, you can get the generic type on the class. If you don't add it, the commented out method cannot get the generic type.
It's hard to understand: I finally understood that if the abstract keyword is added, new is a subclass of the current class. So you can get it. If you don't add it, the current class has no superclass. The direct superclass is java.lang.Object. So it doesn't work.