簡體   English   中英

使用參數化類的Java泛型問題

[英]Java Generics issue with using a parameterized class

所有! 我已經為這件事弄了幾個小時。 很抱歉,這太瑣碎了,但我想我對Java泛型的理解還不夠。 我是Java新手。

我有2個界面。 Int1和Int2。 Int2擴展了Int1。 Int2Impl實現Int2。 下面也給出了Lesson1.java和AnotherClass.java。 課后有問題。

Int1.java

     public interface Int1<E> {
           public Lesson1<E> interfaceimpl(Class<E> klass);
     }

Int2.java

     public interface Int2<E> extends Int1<E> {
         String getSomething();
     }

Lesson1.java

    public class Lesson1<E> {

    }

Int2Impl.java

    public class Int2Impl<E> implements Int2<E> {
        Class<E> klass;

        @Override
        public String getSomething() {
          return "nothing";
        }

        @Override
        public Lesson1<E> interfaceimpl(Class<E> klass) {
            this.klass = klass;
            return null;
        }
   }

AnotherClass.java

  public class AnotherClass<E> {
        private Int2<E> interface2; 

        private <E> void newMethod(Class<E> klass) {
            interface2 = new Int2Impl<>();
          **interface2.interfaceimpl(klass);**

      }
   }

導致編譯問題的代碼行是,

interface2.interfaceimpl(克拉斯); 在類AnotherClass.java中

Eclipse提供的錯誤和快速修復是:

錯誤:

  The method interfaceimpl(java.lang.Class<E>) in the type Int1<E> is not 
  applicable for the arguments (java.lang.Class<E>)

快速修復:

1) Change method interfaceImpl(Class<E>) to interface(Class<E>) 
2) Cast Argument klass to Class<E> 
3) Change type of klass to Class<E>
4) Create method interfaceImpl(Class<E>) in type 'Int2'

快速修復對我來說都沒有意義。 另外,無論我選擇哪一個,他們也無法解決問題。 有人可以指出錯誤,為什么Eclipse會引發此錯誤?

謝謝!

您的AnotherClass已經是通用類型E 無需在方法級別再次定義E

只需從newMethod()刪除<E> ,如下所示:

public class AnotherClass<E> {
    private Int2<E> interface2;

    private void newMethod(Class<E> klass) {
        interface2 = new Int2Impl<>();
        interface2.interfaceimpl(klass);

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM