简体   繁体   中英

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>() {
      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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM