1.工具类,用于获取泛型类的类型和对象
public abstract class FatherReflectUtils<T> { public T getTInstance() throws InstantiationException, IllegalAccessException { Type sType = getClass().getGenericSuperclass(); Type[] generics = ((ParameterizedType) sType).getActualTypeArguments(); Class<T> mTClass = (Class<T>) (generics[0]); return mTClass.newInstance(); } public Class<T> getTClass() throws InstantiationException, IllegalAccessException { Type sType = getClass().getGenericSuperclass(); Type[] generics = ((ParameterizedType) sType).getActualTypeArguments(); Class<T> mTClass = (Class<T>) (generics[0]); return mTClass; } }2.工具子类,继承这个父类,传入泛型的真实类型
public class SonReflectUtils extends FatherReflectUtils<NewsBean> { }
3.使用,即可获取真实类型和对象,可以通过打印日志来验证
SonReflectUtils j = new SonReflectUtils(); try { j.getTClass();
j.getTInstance();} catch (java.lang.InstantiationException e) { e.printStackTrace() ; } catch (IllegalAccessException e) { e.printStackTrace() ; }
在这里存张图片