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

时间:2010-03-16 18:41:07

标签: 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() {
 }
}

我确信这是一个完整的仿制品 - noob问题,但我被困住了。感谢您的任何提示!

0 个答案:

没有答案