Custom AutoClosable in Java
Please go through try-with-resource article on understanding try with resource in java 7
We know that any resource which implements AutoCloseable interface can become a potential candidate for try with resource
Try with resource feature can be used even for custom java class
All we need to do to achieve this is , implement AutoCloseable interface for custom class
AutoCloseable interface contains only one method called close() method
- public interface AutoCloseable {
- public void close() throws Exception;
- }
public interface AutoCloseable { public void close() throws Exception; }
Any java class that we create can implement this AutoCloseable interface and it can be used with try-resource.
Example :
- package com.kb.Exception;
- public class CustomClass implements AutoCloseable {
- public void ExecuteAction() {
- System.out.println("CustomClass executing its action !!");
- }
- @Override
- public void close() throws Exception {
- System.out.println("CustomClass closed!!");
- }
- }
package com.kb.Exception; public class CustomClass implements AutoCloseable { public void ExecuteAction() { System.out.println("CustomClass executing its action !!"); } @Override public void close() throws Exception { System.out.println("CustomClass closed!!"); } }
In the above example, we have written custom class which implements AutoCloseable interface
We have also written executeAction() method just to demonstrate that we can have any other methods in our custom class
Now we can use our custom class inside try-resource as below
- public static void main(String[] args) throws Exception {
- try(CustomClass customClass = new CustomClass()){
- customClass.ExecuteAction();
- }
- }
public static void main(String[] args) throws Exception { try(CustomClass customClass = new CustomClass()){ customClass.ExecuteAction(); } }
We can see that, at the end close() method is called automatically by Java for our custom class as well
This is because our custom class is also implementing AutoCloseable interface
Note :
Try with resource is best to use as it takes care of closing resources no matter whether resource is a java’s built-in class or custom class