有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何声明返回泛型类的方法?

I am new to java i have a set of classes which extends AbsEntity class.I have a abstract method which should return a Class object and that Class object should be E extends AbsEntity type...here is how i am trying to declare

abstract Class<E externds AbsEntity> E getAbsEntity();

这个声明通过我的错误,其实我不知道hw的声明。。。返回类型应为类类型的方法,该类类型为Plz help


共 (3) 个答案

  1. # 1 楼答案

    您可以使用以下代码:

    static <E> E yourMethod(){
        AbsEntity absEntity = new AbsEntity();
        return (E)absEntity;
    }
    
  2. # 2 楼答案

    大概是这样的:

    public <E extends AbsEntity> E yourMethod() {
        //yourObject
        return yourObject;
    }
    
  3. # 3 楼答案

    它应该在返回类型之前声明,如下所示:

        abstract <E extends AbsEntity> Class<E> getAbsEntity();
    

    看看Oracle文档

    希望这有帮助