[英]Annotation to make available generic type
给定一个通用接口
interface DomainObjectDAO<T>
{
T newInstance();
add(T t);
remove(T t);
T findById(int id);
// etc...
}
我想创建一个指定type参数的子接口:
interface CustomerDAO extends DomainObjectDAO<Customer>
{
// customer-specific queries - incidental.
}
实现需要知道实际的模板参数类型,但是当然类型擦除手段在运行时不可用。 我可以包含一些注释来声明接口类型吗? 就像是
@GenericParameter(Customer.class)
interface CustomerDAO extends DomainObjectDAO<Customer>
{
}
然后,实现可以从接口获取此批注,并将其用作运行时泛型类型访问的替代。
一些背景:
此接口使用JDK动态代理为实现概述这里 。 这个接口的非泛型版本运行良好,但使用泛型更好,而不必在子接口中创建方法只是为了指定域对象类型。 泛型和代理处理大多数事情,但在运行时需要实际类型来实现newInstance
方法等。
通过调用以下方法,可以找到Dao子接口(CustomerDAO)的实际类型参数:
import java.lang.reflect.ParameterizedType;
public static Class<?> getDomainClass(final Class<?> daoInterface) {
ParameterizedType type = (ParameterizedType) daoInterface.getGenericInterfaces()[0];
return (Class<?>) type.getActualTypeArguments()[0];
}
当你称之为
Class<?> domainClass = getDomainClass(daoInterface);
使用daoInterface == CustomerDAO.class
,您将获得domainClass == Customer.class
。
在我的实现,一个DaoFactory
执行此调用和使用domainClass
作为一个构造函数参数DaoInvocationHandler
。
实现需要知道实际的模板参数类型。
当然, CustomerDao
任何实现都隐含地知道 type参数是Customer
。 它正在实现DomainObjectDAO<Customer>
而不是DomainObjectDAO<T>
。
如果CustomerDao
类扩展了泛型抽象类,并且该泛型抽象类需要知道T
的实际类型,那么问题才会出现。 但是你可以通过将T
的Class对象(在本例中为Customer.class
)作为构造函数参数传递给超类来处理它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.