Gabriel Petrovay Gabriel Petrovay - 3 months ago 14
Java Question

How to indicate that a Class object should represent a subtype of an interface?

I have the following enum:

public enum NotifierTypes {
EMAIL(EmailNotifier.class);
SMS(SmsNotifier.class)

private final Class internalValue;

NotifierTypes(Class internalValue) {
this.internalValue = internalValue;
}

public Class getNotifierClass() {
return internalValue;
}
}

public interface INotifier {...}
public class EmailNotifier implements INotifier {...}


I want the arguments provided to the constructor to represent types that implement an interface, say
INotifier
. How can I do that?

Answer

Use a generic bound:

private final Class<? extends INotifier> internalName;

NotifierTypes(Class<? extends INotifier> internalName){ /* ... */ }

public Class<? extends INotifier> getIntName(){ /* ... */ }