Java Reference
In-Depth Information
Listing 9-14. An AutoCloseable Resource Class
// MyResource.java
package com.jdojo.exception;
public class MyResource implements AutoCloseable {
private int level;
private boolean exceptionOnClose;
public MyResource(int level, boolean exceptionOnClose) {
this.level = level;
this.exceptionOnClose = exceptionOnClose;
System.out.println("Creating MyResource. Level = " + level);
}
public void use() {
if (level <= 0) {
throw new RuntimeException("Low in level.");
}
System.out.println("Using MyResource level " + this.level);
level--;
}
@Override
public void close() {
if (exceptionOnClose) {
throw new RuntimeException("Error in closing");
}
System.out.println("Closing MyResource...");
}
}
Listing 9-15 shows a simple case of using a MyResource object in a try-with-resources block. The output
demonstrates that the try-with-resources block automatically calls the close() method of the MyResource object.
Listing 9-15. A Simple Use of MyResource Object in a try-with-resources Block
// SimpleTryWithResource.java
package com.jdojo.exception;
public class SimpleTryWithResource {
public static void main(String[] args) {
// Create and use a resource of MyResource type.
// Its close() method will be called automatically */
try (MyResource mr = new MyResource(2, false)) {
mr.use();
mr.use();
}
}
}
 
Search WWH ::




Custom Search