SeleniumのWebDriverの閉じ忘れ防止のため、AutoCloseableを実装するラッパを作っていました。以下の様なコードです。
import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.internal.FindsById; import java.util.List; import java.util.Set; public class AutoCloseableDriver implements WebDriver, JavascriptExecutor, FindsById , AutoCloseable { private ChromeDriver webDriver; AutoClosableDriver(ChromeDriver webDriver) { this.webDriver = webDriver; } @Override public void get(String s) { this.webDriver.get(s); } @Override public String getCurrentUrl() { return this.webDriver.getCurrentUrl(); } @Override public String getTitle() { return this.webDriver.getTitle(); } @Override public List findElements(By by) { return this.webDriver.findElements(by); } @Override public WebElement findElement(By by) { return this.webDriver.findElement(by); } @Override public String getPageSource() { return this.webDriver.getPageSource(); } @Override public void close() { this.webDriver.close(); } @Override public void quit() { this.webDriver.quit(); } @Override public Set getWindowHandles() { return this.webDriver.getWindowHandles(); } @Override public String getWindowHandle() { return this.webDriver.getWindowHandle(); } @Override public TargetLocator switchTo() { return this.webDriver.switchTo(); } @Override public Navigation navigate() { return this.webDriver.navigate(); } @Override public Options manage() { return this.webDriver.manage(); } @Override public Object executeScript(String s, Object... objects) { return this.webDriver.executeScript(s, objects); } @Override public Object executeAsyncScript(String s, Object... objects) { return this.webDriver.executeAsyncScript(s, objects); } @Override public WebElement findElementById(String s) { return webDriver.findElementById(s); } @Override public List findElementsById(String s) { return webDriver.findElementsById(s); } }
コンストラクタで渡されたWebDriverに全ての処理を委譲するだけです。
ありがち、かつ冗長なのでKotlinではDelegationという便利な機能があって、こんなに短くなります。
import org.openqa.selenium.JavascriptExecutor import org.openqa.selenium.WebDriver import org.openqa.selenium.chrome.ChromeDriver import org.openqa.selenium.internal.FindsById class AutoCloseableDriver constructor(private val webDriver: ChromeDriver) : WebDriver by webDriver, JavascriptExecutor by webDriver, FindsById by webDriver, AutoCloseable