Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 有可能在泛型中引入泛型吗?_Java_Generics_Type Erasure - Fatal编程技术网

Java 有可能在泛型中引入泛型吗?

Java 有可能在泛型中引入泛型吗?,java,generics,type-erasure,Java,Generics,Type Erasure,对不起,瓷砖。。。我不知道如何继续我的问题 让我介绍一下我的问题: 我想得到泛型类型的类型 一些代码: public class AbstractDao<T, PK extends Serializable> { public T getByPrimaryKey(PK primariKey) { return null; } } public class AbstractEntity<PK extends Serializable> {

对不起,瓷砖。。。我不知道如何继续我的问题

让我介绍一下我的问题:

我想得到泛型类型的类型

一些代码:

public class AbstractDao<T, PK extends Serializable> {
    public T getByPrimaryKey(PK primariKey) {
    return null;
    }
}

public class AbstractEntity<PK extends Serializable> {
    PK id;
    //Getter Setter
}

public class Entity extends AbstractEntity<Long> {
}
谢谢你的帮助


如果您不想要泛型PK类型,那么您可以创建一个PrimaryKey接口作为实际主键的包装器,使用各种实现,例如LongPrimaryKey等。这样您就可以避免泛型类型


但是,如果您希望能够传递实际类型本身,例如Long,那么我看不到绕过泛型类型的方法,在我看来,泛型类型的位置很好。

如果您创建AbstractDao的具体实例,java可以确定其泛型类型

类ParameteredType getClass.getGenericSuperclass.getActualTypeArguments[0]


将为您提供第一个泛型参数的运行时类型。这并不总是可用的,所以请查看文档和。

我们的想法是从AbstractService中删除PK extends Serializable并动态地获取它。什么意思,动态获取?您想用它做什么?从何处动态获取它?对于当前代码,您不喜欢的是什么?
 public class AbstractService<T, PK extends Serializable> {
    AbstractDao<T, PK> dao;

    public T getByPrimaryKey(final PK primaryKey) {
        return dao.getByPrimaryKey(primaryKey);
    }
 }

 public class EntityService extends AbstractService<Entity, Long> {}
public T getByPrimaryKey(final PK primaryKey)