匿名类如何实现两个(或更多)接口?或者,它如何既扩展一个类又实现一个接口?例如,我想创建一个扩展两个接口的匿名类对象:
// 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;
}
}
};
然后我可以在 try-with-resources 块中使用它AutoCloseable
作为延迟初始化的实用程序类:
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
类型)。