Subscribe to RSS

Some rights reserved

Except where otherwise noted, content on this site is licensed under a Creative Commons License


blog‎ > ‎

Duck typing... in Java

posted Oct 11, 2009 2:53 PM by Davide Angelocola   [ updated Oct 11, 2009 3:02 PM ]
A quick hack in Java, it comes handy when supporting old Java code (pre Java 5, where Closeable is missing):

public static void universalClose(Object o) {
    try {
        o.getClass().getMethod("close", null).invoke(o, null);
    } catch (Exception e) {
        throw new IllegalArgumentException("no close() method");
    }
}
    
testcase:
    
public static void main(String[] args) {
    Socket socket = new Socket();
    universalClose(socket);
}