Consider the following program:
import java.util.List;
import java.util.ArrayList;
public class TypeTest {
public static class TypeTestA extends TypeTest {
}
public static class TypeTestB extends TypeTest {
}
public static final class Printer {
public void print(TypeTest t) {
System.out.println("T");
}
public void print(TypeTestA t) {
System.out.println("A");
}
public void print(TypeTestB t) {
System.out.println("B");
}
public <T extends TypeTest> void print(List<T> t) {
for (T tt : t) {
print(normalize(tt.getClass(), tt));
}
}
private static <T> T normalize(Class<T> clz, Object o) {
return clz.cast(o);
}
}
public static void main(String[] args) {
Printer printer = new Printer();
TypeTest t1 = new TypeTest();
printer.print(t1);
TypeTestA t2 = new TypeTestA();
printer.print(t2);
TypeTestB t3 = new TypeTestB();
printer.print(t3);
System.out.println("....................");
List<TypeTestB> tb1 = new ArrayList<TypeTestB>();
tb1.add(t3);
printer.print(tb1);
}
}
The main method now prints:
T
A
B
....................
T
What should I do to make it print the followings?
T
A
B
....................
B
I'd like to avoid writing a loop such as the following for each of the type that can be printed:
public void printTypeTestB(List<TypeTestB> t) {
for (TypeTestB tt : t) {
print(tt);
}
}