[英]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.