0

我有一个有界泛型类,我们称它为 Generic,带有一个扩展抽象类 Abstract 的参数 T:

通用类:

public class Generic<T extends Abstract> { 
   
   public <T extends Abstract> List<T> method() {
   
      Map<String,String> map = T.getMap(); //this is the line with the error. I'll explain it below

      //return statement and such
   }
}

抽象类


public abstract class Abstract {
   protected Map<String, String> map;

   public abstract Map<String, String> getMap();
}

泛型类中 T 引用的类

public class class1 extends Abstract {
   
   public class1() {
   //map is inmutably defined here and assigned to the super
   }

   @Override
   public Map<String, String> getMap() {
   return super.map;
   }
}

当尝试引用来自 T 边界内的类的方法 getMap() 时(并且根据抽象类定义,所有可能的 T 实例都将具有该方法,我收到以下错误:

不能从静态上下文引用非静态方法 getMap()

然而,任何地方都没有静态关键字。我错过了什么??

谢谢!

4

1 回答 1

0

因为该方法getMap()是一个实例方法(即不是static),所以如果要调用该方法,则需要一个实例T


你的类层次结构看起来也很奇怪。我认为您实际上想要更多类似的东西:

public class Generic<T> extends Abstract<T> { 

}

public abstract class Abstract<T> {
    protected Map<String, T> map;
}

但如果没有您的意图背景,我无法确定。

于 2020-09-01T01:35:55.560 回答