@SPI
public interface Animal {
void makeSound();
}
@SPIImplementation
public class Dog implements Animal {
@Override
public void makeSound() {
}
}
@SPIImplementation
public class Cat implements Animal {
@Override
public void makeSound() {
}
}
public class Application {
public static void main(String[] args) {
Animal animal = SPIFactory.getServiceImpl(Animal.class);
animal.makeSound();
}
}
public class SPIFactory {
public static <T> T getServiceImpl(Class<T> clazz) {
String spiValue = SPIUtil.getSPIValue(clazz);
try {
Class<?> implClass = Class.forName(spiValue);
return (T) implClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class SPIUtil {
public static String getSPIValue(Class<?> clazz) {
SPI spi = clazz.getAnnotation(SPI.class);
throw new IllegalArgumentException("SPI value is not specified");
}
return spi.value();
}
}