使用泛型类型的 Java 构造函数

发布于 2024-08-25 08:05:32 字数 1372 浏览 3 评论 0原文

我很难理解 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文