import org.reflections.Reflections; public final class BrowserFactory { private boolean isHeadless; public BrowserFactory setHeadless(boolean isHeadless) { this.isHeadless = isHeadless; return this; } public WebDriver getInstance(String browserName) throws Exception { // Returns a List of classes that derives from Browser using Generics and Reflection // The ? is a bounded wildcard which denotes an unknown type List> browsers = new ArrayList<>( new Reflections(Browser.class.getPackageName()).getSubTypesOf(Browser.class)); // Filters the List for the class containing the browserName, instantiates the class, and gets the WebDriver return browsers.stream().filter(b -> b.getSimpleName().toLowerCase().contains(browserName.toLowerCase())) .findFirst().orElseThrow(() -> new RuntimeException("Browser not supported!")).getConstructor() .newInstance().getDriver(isHeadless); } }