C# Java中的贷款模式/自动资源管理
我曾尝试为Java实现自动资源管理(类似于C#sC# Java中的贷款模式/自动资源管理,c#,java,C#,Java,我曾尝试为Java实现自动资源管理(类似于C#s使用)。以下是我提出的代码: 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) {
使用
)。以下是我提出的代码:
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>() {
public void use(PrintWriter writer) {
writer.println("Hello");
}
});
}
}
import java.lang.reflect.*;
导入java.io.*;
界面资源用户{
无效使用(T资源);
}
类LoanPattern{
使用(T资源、资源用户)的公共静态void{
方法closeMethod=null;
试一试{
closeMethod=resource.getClass().getMethod(“close”);
用户使用(资源);
}
捕获(异常x){
x、 printStackTrace();
}
最后{
试一试{
调用(资源);
}
捕获(异常x){
x、 printStackTrace();
}
}
}
公共静态void main(字符串[]args){
使用(new PrintWriter(System.out,true),new ResourceUser(){
公共作废使用(打印器){
writer.println(“你好”);
}
});
}
}
请分析以上代码,让我知道任何可能的缺陷,并建议我如何改进。多谢各位
(对不起,我的英语很差。我不是以英语为母语的人。)我会使用以下方法修改您的
:
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
}
}
}
publicstaticvoid使用(T资源、资源用户){
试一试{
用户使用(资源);
}最后{
试一试{
方法closeMethod=resource.getClass().getMethod(“close”);
调用(资源);
}捕获(无此方法例外){
//不可关闭
}捕获(安全异常e){
//不可关闭
}
}
}
此外,您还需要为资源不可关闭的情况(捕获上述异常时)定义所需的行为。您可以抛出一个特定的异常,如UnclosableSourceException
,也可以完全忽略这种情况。您甚至可以使用这两种行为实现两种方法(使用
和尝试
)。我想说的一个问题是,您的ResourceUser方法无法返回值。在很多情况下,你可能会想要这样。这应该很容易。我不认为忽视是一个有效的选择。将未定义close方法的内容传递给该方法将是一个编程错误,如果您认为某个内容正在关闭,但它没有关闭,则会导致错误被忽略。更不用说每次创建异常的成本了。