I have been struggling for some time trying to define a generic interface, but I fail to achieve what I want. The following is a simplified example of the problem.
Let's say I have a generic Message class
public class Message<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
and then I want to define an interface for transfering things:
public interface Transfer<Message<T>> {
public void send(Message message);
}
The problem is that the compiler does not accept this, and always complains about the second '<' character, no matter what variations I try. How do I specify this interface so that it is bound to a generic type (based on Message) and also have access to the parameterized type?
My plan was to use this interface like the following:
public class Carrier<Message<T>> implements Transfer<Message<T>> {
public void send(Message message) {
T content = message.getContent();
print(content);
}
public static void print(String s) {
System.out.println("The string equals '" + s + "'");
}
public static void print(Integer i) {
System.out.println("The integer equals " + i);
}
public static void main(String[] args) {
Carrier<Message<String>> stringCarrier = new Carrier<Message<String>>();
Message<String> stringMessage = new Message<String>("test");
stringCarrier.send(stringMessage);
Carrier<Message<Integer>> integerCarrier = new Carrier<Message<Integer>>();
Message<Integer> integerMessage = new Message<Integer>(123);
integerCarrier.send(integerMessage);
}
}
I have done some searching and reading (among other things Angelika's generics faq), but I am not able to tell if this is not possible or if I am doing it wrong.
Update 2009-01-16: Removed the original usage of "Thing" instead of "Message< T >" (which was used because with that I was able to compile without getting syntax errors on the interface).