Loan Pattern / Automatic Resource Management in Java
I have tried to implement automatic resource management for Java (something like C#'s using
). Following is the code I have come up with:
import java.lang.reflect.*;
import java.io.*;
interface ResourceUser<T> {
void use(T resource);
}
class LoanPattern {
public static <T> void using(T resource, ResourceUser<T> user) {
Method closeMethod = null;
try {
closeMethod = resource.getClass().getMethod("close");
user.use(resource);
}
catch(Exception x) {
x.printStackTrace();
}
finally {
try {
closeMethod.invoke(resource);
}
catch(Exception x) {
x.printStackTrace();
}
}
}
public static void main(String[] args) {
using(new PrintWriter(System.out,true), new ResourceUser<PrintWriter>开发者_C百科;() {
public void use(PrintWriter writer) {
writer.println("Hello");
}
});
}
}
Please analyze the above code and let me know of any possible flaws and also suggest how I can improve this. Thank you.
(Sorry for my poor English. I am not a native English speaker.)
I would modify your using
method like:
public static <T> void using(T resource, ResourceUser<T> user) {
try {
user.use(resource);
} finally {
try {
Method closeMethod = resource.getClass().getMethod("close");
closeMethod.invoke(resource);
} catch (NoSuchMethodException e) {
// not closable
} catch (SecurityException e) {
// not closable
}
}
}
Also, you need to define the behavior you want for the case that the resource is not closable (when you catch the above exceptions). You can either throw a specific exception like UnclosableResourceException
or completely ignore this case. You can even implement 2 methods with these 2 behaviors (using
and tryUsing
).
精彩评论