interface BaseDao<T> { }
interface UserDao extends BaseDao<User> { }
interface DeptDao extends BaseDao<Department> { }
我需要一个Entity
通过Dao
类获取函数的函数,像这样:
func(UserDao.class) return User.class
func(DeptDao.class) return Deparment.class
而且我不喜欢添加annotation
到dao
,就像这样:
@Entity(User.class)
interface UserDao extends BaseDao
受dimo414的建议启发,这是我的解决方案:
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class Main {
public static void main(String[] args) {
// if A and B are Class, then it be 'B.class.getGenericSuperclass()'
Type genType = B.class.getGenericInterfaces()[0];
if (genType instanceof ParameterizedType) {
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
Class<?> clz = (Class) params[0];
System.out.println(clz); // class java.lang.String
}
}}
interface A<T> {}
interface B extends A<String> {}
看一下Guava的TypeToken
,它所做的(我认为)是您正在描述的。有关“反射说明”的更多信息,请参见。
该TypeCapture.capture()
方法获取父类的泛型类型:
Type capture() {
Type superclass = getClass().getGenericSuperclass();
checkArgument(superclass instanceof ParameterizedType, "%s isn't parameterized", superclass);
return ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
这就是TypeToken
“魔术”的原理。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句