是否可以在Java中创建泛型类型的实例?我正在考虑基于我所看到的答案是no(由于类型擦除),但如果有人能看到我缺少的东西,我会感兴趣:
class SomeContainer<E>
{
E createContents()
{
return what???
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:事实证明,超级类型标记可用于解决我的问题,但它需要大量基于反射的代码,如下面的一些答案所示.
我会把这个开放一段时间,看看是否有人提出了与Ian Robertson的Artima文章截然不同的任何东西.
我使用泛型创建了接口和类的层次结构,并搞砸了所有内容.
最顶级的类是AbstractJpaEntity,它由所有域实体扩展
@MappedSuperclass
@EntityListeners({AbstractJpaEntity.AbstractEntityListener.class})
@SuppressWarnings("serial")
public class AbstractJpaEntity implements Serializable
Run Code Online (Sandbox Code Playgroud)
ProductTypeDomain类就像分隔出几个表实体的标记类一样.
@SuppressWarnings("serial")
@MappedSuperclass
@EntityListeners({ ProductTypeDomain.AbstractEntityListener.class })
public class ProductTypeDomain extends AbstractJpaEntity{}
Run Code Online (Sandbox Code Playgroud)
接口"GenericDao"定义
public interface GenericDao<T> {...
Run Code Online (Sandbox Code Playgroud)
抽象类GenericDaoImpl(此类具有通用函数,如persist,merge)
public abstract class GenericDaoImpl<T extends AbstractJpaEntity> implements GenericDao<T> {...
Run Code Online (Sandbox Code Playgroud)
接口ProductTypeDao
public interface ProductTypeDao<T extends ProductTypeDomain> extends GenericDao<T> {
Run Code Online (Sandbox Code Playgroud)
Spring存储库类ProductTypeDaoImpl
@Repository("productTypeDao")
public class ProductTypeDaoImpl extends GenericDaoImpl implements ProductTypeDao
{....
Run Code Online (Sandbox Code Playgroud)
在Spring服务类ProductManagerServiceimpl中,我是自动装配存储库productTypeDao
@Service("productManager")
public class ProductManagerServiceimpl implements ProductManagerService{
@Autowired
ProductTypeDao productTypeDao;
Run Code Online (Sandbox Code Playgroud)
在运行代码时,它给了我以下错误
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.jodo.cms.service.ProductManagerService com.jodo.cms.controllers.ProductController.productManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error …
我想通过定义泛型类的类型来创建一个实例
public abstract class Base<T> {
private final T genericTypeObject;
protected Base(){
//Create instance of T here without any argument
}
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以调用默认构造函数:
public class Child extends Base<SomeClass>{
public Child () {
super();
}
}
Run Code Online (Sandbox Code Playgroud)
基类实现将为我创建一个 GenericType 的实例。