使用泛型类型的 Java 构造函数
我很难理解 Java 泛型类型。这是一段简单的代码,在我看来应该可以工作,但我显然做错了什么。
Eclipse 在 BreweryList.java 中报告此错误:
The method initBreweryFromObject() is undefined for the type <T>
这个想法是用 Brewery 类的子类对象的实例填充 Vector,因此调用将类似于:
BreweryList breweryList = new BreweryList(BrewerySubClass.class, list);
BreweryList.java
package com.beerme.test;
import java.util.Vector;
public class BreweryList<T extends Brewery> extends Vector<T> {
public BreweryList(Class<T> c, Object[] j) {
super();
for (int i = 0; i < j.length; i++) {
T item = c.newInstance();
// initBreweryFromObject() is an instance method
// of Brewery, of which <T> is a subclass (right?)
c.initBreweryFromObject();
// "The method initBreweryFromObject() is undefined
// for the type <T>"
}
}
}
Brewery.java
package com.beerme.test;
public class Brewery {
public Brewery() {
super();
}
protected void breweryMethod() {
}
}
BrewerySubClass.java
package com.beerme.test;
public class BrewerySubClass extends Brewery {
public BrewerySubClass() {
super();
}
public void androidMethod() {
}
}
我确信这是一个完全泛型菜鸟的问题,但我被卡住了。感谢您的任何提示!
I'm having a hard time wrapping my head around Java generic types. Here's a simple piece of code that in my mind should work, but I'm obviously doing something wrong.
Eclipse reports this error in BreweryList.java:
The method initBreweryFromObject() is undefined for the type <T>
The idea is to fill a Vector with instances of objects that are a subclass of the Brewery class, so the invocation would be something like:
BreweryList breweryList = new BreweryList(BrewerySubClass.class, list);
BreweryList.java
package com.beerme.test;
import java.util.Vector;
public class BreweryList<T extends Brewery> extends Vector<T> {
public BreweryList(Class<T> c, Object[] j) {
super();
for (int i = 0; i < j.length; i++) {
T item = c.newInstance();
// initBreweryFromObject() is an instance method
// of Brewery, of which <T> is a subclass (right?)
c.initBreweryFromObject();
// "The method initBreweryFromObject() is undefined
// for the type <T>"
}
}
}
Brewery.java
package com.beerme.test;
public class Brewery {
public Brewery() {
super();
}
protected void breweryMethod() {
}
}
BrewerySubClass.java
package com.beerme.test;
public class BrewerySubClass extends Brewery {
public BrewerySubClass() {
super();
}
public void androidMethod() {
}
}
I'm sure this is a complete-generics-noob question, but I'm stuck. Thanks for any tips!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论