匿名クラスで 2 つ (またはそれ以上) のインターフェイスを実装するにはどうすればよいですか? あるいは、クラスの拡張とインターフェースの実装の両方を行うにはどうすればよいでしょうか? たとえば、2 つのインターフェイスを拡張する匿名クラスのオブジェクトを作成したいとします。
// Java 10 "var" is used since I don't know how to specify its type
var lazilyInitializedFileNameSupplier = (new Supplier<String> implements AutoCloseable)() {
private String generatedFileName;
@Override
public String get() { // Generate file only once
if (generatedFileName == null) {
generatedFileName = generateFile();
}
return generatedFileName;
}
@Override
public void close() throws Exception { // Clean up
if (generatedFileName != null) {
// Delete the file if it was generated
generatedFileName = null;
}
}
};
AutoCloseable
次に、遅延初期化されたユーティリティ クラスとして、try-with-resources ブロックで使用できます。
try (lazilyInitializedFileNameSupplier) {
// Some complex logic that might or might not
// invoke the code that creates the file
if (checkIfNeedToProcessFile()) {
doSomething(lazilyInitializedFileNameSupplier.get());
}
if (checkIfStillNeedFile()) {
doSomethingElse(lazilyInitializedFileNameSupplier.get());
}
}
// By now we are sure that even if the file was generated, it doesn't exist anymore
このクラスは、それを使用する必要があるメソッド以外のどこでも使用されないことが確実であるため、内部クラスを作成したくありません (また、そのメソッドで宣言されたローカル変数を使用することもできます。タイプであることvar
)。