代码之家  ›  专栏  ›  技术社区  ›  Andrei Fierbinteanu

Sun JDK 1.5不能用泛型取消引用错误

  •  6
  • Andrei Fierbinteanu  · 技术社区  · 15 年前

    我们有一个类似的类层次结构:

    public class TestDereference {
     private static MainInterface mi = new MainInterfaceImpl();
    
     public static void main(String[] args) {
      System.out.println(mi.getSubInterface().getField());
     }
    }
    
    interface MainInterface {
     <T extends SubInterface> T getSubInterface();
    }
    
    interface SubInterface {
     Field getField();
    }
    
    class Field {
     @Override
     public String toString() {
      return "Hooray!";
     }
    }
    
    class SubInterfaceImpl implements SubInterface {
     Field f = new Field();
    
     public Field getField() {
      return f;
     }
    
    }
    
    class MainInterfaceImpl implements MainInterface {
     SubInterfaceImpl si = new SubInterfaceImpl();
    
     public <T extends SubInterface> T getSubInterface() {
      return (T) si;
     }
    }
    

    接口实际上有多个实现,但这不是问题所在。使用Eclipse编译器或Java 1.6编译它可以很好地工作(如上所示 ideone

    TestDereference.java:12: test.SubInterface cannot be dereferenced
                    System.out.println(mi.getSubInterface().getField());
                                                         ^
    

    还要注意,JDK 1.6使用 -target 1.5 或者,只有JDK1.5

    我在网上发现的唯一一个出现此错误的情况与执行以下操作有关:

    double d = 2.0;
    d.toString();
    

    但这是我的案子,应该行得通,因为很明显 getSubInterface() SubInterface 实现类 getField()

    这是编译器的错误吗?我还有什么选择 mi.<SubInterface>getSubInterface()

    2 回复  |  直到 15 年前
        1
  •  1
  •   dacwe    15 年前

    检查错误: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5003431

    选择一:

    SubInterface si = mi.getSubInterface();
    si.getField();
    

    选项二:

    mi.<SubInterface>getSubInterface().getField()
    
        2
  •  1
  •   Luke Hutteman    15 年前

    我想这是一个在Java6中修复的错误。

    按如下方式重写主方法将使Java5和Java6都能正常工作:

    public static void main(String[] args) {
        SubInterface subInterface = mi.getSubInterface();
        System.out.println(subInterface.getField());
    }
    

    似乎Java5需要赋值来正确地派生类型 T ,即使它已经声明要扩展 SubInterface

    推荐文章