Credit Template / Automatic Resource Management in Java

I tried to implement automatic resource management for Java (something like C # using). Below is the code I came 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");
      }
    });
  }
}

Analyze the code above and let me know about any possible flaws, and also suggest how I can improve this. Thank.

(Sorry for my poor English. I am not a native speaker of English.)

+3
source share
1 answer

I would change your method using, for example:

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
        }
    }
}

, , , ( ). , UnclosableResourceException, . 2 2 (using tryUsing).

+2

Source: https://habr.com/ru/post/1738975/


All Articles