简体   繁体   English

使用参数化类的Java泛型问题

[英]Java Generics issue with using a parameterized class

All! 所有! I have breaking my head over this things for a few hours now. 我已经为这件事弄了几个小时。 I'm sorry if it's something so trivial but I guess I don't understand Java generics well enough. 很抱歉,这太琐碎了,但我想我对Java泛型的理解还不够。 I'm a novice Java programmer. 我是Java新手。

I have 2 interfaces. 我有2个界面。 Int1 and Int2. Int1和Int2。 Int2 extends Int1. Int2扩展了Int1。 Int2Impl implements Int2. Int2Impl实现Int2。 Lesson1.java and AnotherClass.java are given below also. 下面也给出了Lesson1.java和AnotherClass.java。 Questions follow after the classes. 课后有问题。

Int1.java Int1.java

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

Int2.java Int2.java

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

Lesson1.java Lesson1.java

    public class Lesson1<E> {

    }

Int2Impl.java 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 AnotherClass.java

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

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

      }
   }

The line of code that's causing a compilation issue is, 导致编译问题的代码行是,

interface2.interfaceimpl(klass); interface2.interfaceimpl(克拉斯); in the class AnotherClass.java 在类AnotherClass.java中

the errors and the quickfixes that Eclipse offers are: Eclipse提供的错误和快速修复是:

Error: 错误:

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

Quick Fixes: 快速修复:

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'

None of the quick fixes make sense to me. 快速修复对我来说都没有意义。 Plus they also don't fix the problem regardless of which one I choose. 另外,无论我选择哪一个,他们也无法解决问题。 Can someone point out the mistake and why Eclipse throws this error? 有人可以指出错误,为什么Eclipse会引发此错误?

Thanks! 谢谢!

Your AnotherClass is already of generic type E . 您的AnotherClass已经是通用类型E No need to define E again at method level. 无需在方法级别再次定义E

Just remove <E> from your newMethod() as follows: 只需从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