Java: class <T> and class: difference when using from / outside the class
I have a class that should use the Class<T> parameter (see my previous semi-connected question ). It:
public class BaseTable<T extends TableEntry> { protected Class<T> mClass; ... public BaseTable(int rows, int cols, Class<T> clasz) { ... mClass = clasz; } public BaseTable(int rows, int cols) { this(rows, cols, StringTableEntry.class); //Does NOT compile: //expected [int, int, Class<T>], but got //[int, int, Class<blah.blah.StringTableEntry>] } ... } I am wondering why the constructor (with two parameters) does not work, but when I call the same from an external class, for example:
mSomeTable = new BaseTable<StringTableEntry>(2, 2, StringTableEntry.class); It compiles and runs without complaint. Why and how to get around this?
Thanks!
+4
1 answer
A class constructor that has common type parameters can be used to build this class with any types (which correspond to the boundaries in the class declaration). So what happens if someone says:
new BaseTable<SomeTypeUnrelatedToStringTableEntry>(rows, cols) ?
As a workaround, use the static factory method:
public static BaseTable<StringTableEntry> newStringTableEntryBaseTable( int rows, int cols) { return new BaseTable<StringTableEntry>(rows, cols, StringTableEntry.class); } Or you can create a subclass:
class StringTableEntryBaseTable extends BaseTable<StringTableEntry> { StringTableEntryBaseTable(int rows, int cols) { super(rows, cols, StringTableEntry.class); } } +4