How to extract class from Java generic class to satisfy compiler?
You can avoid unnecessary casts! See below:
public static class MessageType<T> {
static MessageType<List<String>> STRINGS_LIST_TYPE1 = new MessageType<>(List.class);
static MessageType<List<String>> STRINGS_LIST_TYPE2 = new MessageType<>();
static MessageType<Double> DOUBLE_TYPE = new MessageType<>(Double.class);
static MessageType<String> STRING_TYPE = new MessageType<>(String.class);
List<T> messages = new ArrayList<>();
Class<T> clazz;
@SuppressWarnings({"rawtypes","unchecked"})
MessageType(Class<? extends T> clazz) { this.clazz = (Class) clazz; }
MessageType() { this.clazz = null; }
void addMessage(T message) { messages.add(message); }
T getMessage(int i) { return messages.get(i); }
Class<T> getClazz() { return this.clazz; }
public static void main(String[] args) {
// MessageType<List<String>> STRINGS_LIST_TYPE1 = new MessageType<>(List.class);
STRINGS_LIST_TYPE1.addMessage(new ArrayList<String>()); // no compile issues
STRINGS_LIST_TYPE1.addMessage(new ArrayList<Integer>()); // compile error "not applicable for the arguments (ArrayList<Integer>)"
List<String> message1 = STRINGS_LIST_TYPE1.getMessage(0); // no warnings!
Class<List<String>> clazz1 = STRINGS_LIST_TYPE1.getClazz(); // no warnings!
// MessageType<List<String>> STRINGS_LIST_TYPE2 = new MessageType<>()
STRINGS_LIST_TYPE2.addMessage(new ArrayList<String>()); // no compile issues
STRINGS_LIST_TYPE2.addMessage(new ArrayList<Integer>()); // compile error "not applicable for the arguments (ArrayList<Integer>)"
List<String> message2 = STRINGS_LIST_TYPE2.getMessage(0); // no warnings!
Class<List<String>> clazz2 = STRINGS_LIST_TYPE2.getClazz(); // no warnings! but returns null
}
}