Java constructor using generic types
Posted
by user37903
on Stack Overflow
See other posts from Stack Overflow
or by user37903
Published on 2010-03-16T18:41:07Z
Indexed on
2010/03/17
8:01 UTC
Read the original article
Hit count: 189
java
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!
© Stack Overflow or respective owner