【问题标题】:Java Generics, define type during method callJava 泛型,在方法调用期间定义类型
【发布时间】:2014-05-28 19:21:19
【问题描述】:

我有两个静态方法:

  public static Selector<TextView, Property<String>> textView(
          final Selector<TextView, Property<TextView>> selector) {
    return null;
  }

  public static <V extends View> Selector<V, Property<V>> withId(final int id) {
    return null;
  }

为什么Java编译器在调用过程中不能解析出所需的参数类型???

textView(withId(R.id.et_password));

但很容易接受这一点:

Selector<TextView, Property<TextView>> p;
textView((p = withId(R.id.et_password));

谁能提示我如何欺骗编译器?

附: class TextView extends View { ... }

【问题讨论】:

  • View 是否扩展 TextView?
  • 对,TextView 类扩展 View { ... }

标签: java android generics casting type-conversion


【解决方案1】:

您需要为这种情况提供显式类型参数。语法是:

textView(MainActivity.<TextView>withId(R.id.et_password));      

假设MainActivity 是具有这些方法的类(不能省略,即使此代码在类中)。

如果withId 是实例方法而不是静态方法,那么它将是:

textView(this.<TextView>withId(R.id.et_password));

您可以查看this answer 以了解原因。这种特殊情况的不同之处在于&lt;V extends View&gt; Selector&lt;V, Property&lt;V&gt;&gt; 的擦除是Selector&lt;View, Property&lt;View&gt;&gt;(而不是&lt;Object&gt;,仅仅是因为已知V 扩展了View)。

如您所见,这正是编译器显示的错误:

方法 textView(Selector&lt;TextView,Property&lt;TextView&gt;&gt;) 不适用于论点 (Selector&lt;View,Property&lt;View&gt;&gt;)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多