Custom AutoCloseable Java 7 Example - Java @ Desk

Thursday, July 31, 2014

Custom AutoCloseable Java 7 Example

Custom AutoCloseable Java 7 Example

A new interface called java.lang.AutoCloseable was introduced in Java 7. All the resources like Streams, Connections in java implements this interface. We already saw three resources, Result set, connection , Statement. Dataoutputstream, FileOutputStreram are other examples of implementation of this resources.

Autocloseable interface has a method called close() that may throw checked exception. Such close() methods have been retro-fitted into many classes , including the

1) java.io
2) java.nio
3) javax.crypto
4) java.security
5) java.util.zip
6) java.util.jar
7) javax.net
8) java.sql packages

The AutoClosable interface only has a single method called close(). Here is how the interface looks:

public interface AutoClosable {
    public void close() throws Exception;
}


So, if we have to create a custom autoclose implementation we will have to implement autocloseable interface as shown below :

public class CustomConnectionImpl implements AutoCloseable {

 @Override
    public void close() {
        System.out.println("Closing new connection()");
        
    }
    
    public void open() throws MyException1 {
        System.out.println("Opening new connection()");
        
    }
    
    public static void main(String[] args) {
        try (CustomConnectionImpl autoClose = new CustomConnectionImpl()) {
            autoClose.open();
        } catch (MyException1 e) {
            e.printStackTrace();
        }
    }
}
    
    class MyException1 extends Exception {
        
        public MyException1() {
            super();
        }
        
        public MyException1(String message) {
            super(message);
        }
    }


Running the above main file will generate below output :

Output:
Opening new connection()
Closing new connection()


This post is written by Dipika Mulchandani. She is a freelance writer, loves to explore latest features in Java technology.





No comments:

Post a Comment