全部!我已经为这件事伤透了几个小时了。如果事情如此琐碎,我很抱歉,但我想我对 Java 泛型的理解还不够好。我是一名 Java 程序员新手。
我有 2 个接口(interface)。 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;
}
}
另一个类.java
public class AnotherClass<E> {
private Int2<E> interface2;
private <E> void newMethod(Class<E> klass) {
interface2 = new Int2Impl<>();
**interface2.interfaceimpl(klass);**
}
}
导致编译问题的代码行是,
interface2.interfaceimpl(klass);在 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
再次在方法级别。
只需删除 <E>
来自您的newMethod()
如下:
public class AnotherClass<E> {
private Int2<E> interface2;
private void newMethod(Class<E> klass) {
interface2 = new Int2Impl<>();
interface2.interfaceimpl(klass);
}
}
关于使用参数化类的 Java 泛型问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462413/