patternjavaModerate
Closeable to AutoCloseable converter utility for 3rd party java libs
Viewed 0 times
autocloseable3rdpartyutilityjavalibsforconvertercloseable
Problem
I made this utility class to convert Closeable instances to AutoCloseable, so that I can make use of the try-with-resource exception handling mechanism of Java7. This is mainly useful for code which can not be altered.
usage can be like :
feedback much appreciated.
public class AutoClose implements AutoCloseable, Closeable {
public final T instance;
private AutoClose(T instance) {
this.instance = instance;
}
public static AutoClose of(T instance) {
return new AutoClose<>(instance);
}
@Override
public void close() throws IOException {
instance.close();
}
}usage can be like :
try (AutoClose auto = AutoClose.of(someCloseable)) {
auto.instance.someWork();
}feedback much appreciated.
Solution
I'll try to say this the best way I can...
Completely useless unnecessary!
Sorry. I couldn't find any better way to say it. The code that you have is well-written, but it is not necessary in the first place.
The reason is that the interface Closeable already lists
Which means that your code:
Can instead be simply:
There is no need for your
Completely useless unnecessary!
Sorry. I couldn't find any better way to say it. The code that you have is well-written, but it is not necessary in the first place.
The reason is that the interface Closeable already lists
AutoCloseable as a "superinterface", which means that Closeable extends AutoCloseable. So all Closeable objects are already AutoCloseable.Which means that your code:
try (AutoClose auto = AutoClose.of(someCloseable)) {
auto.instance.someWork();
}Can instead be simply:
try (SomeType auto = someCloseable) {
auto.someWork();
}There is no need for your
AutoClose wrapper.Code Snippets
try (AutoClose<SomeType> auto = AutoClose.of(someCloseable)) {
auto.instance.someWork();
}try (SomeType auto = someCloseable) {
auto.someWork();
}Context
StackExchange Code Review Q#142001, answer score: 12
Revisions (0)
No revisions yet.