java - generics method for closing resource files -


i have cursors, inputstreams, outputstreams instead of doing .close() each one, call method on them closes them.

i tried :

private static void closeresource ( object<t>  item )     {         try         {             if ( item != null )             {                 item.close();             }         }         catch ( exception e )         {             throw new runtimeexception( e );         }     } 

it doesn't work.. object not generic.

  1. object not generic type can't use object<t>.
  2. the object class has no close method defined in it.

the generics-oriented solution define generic method type parameter bound closeable interface declares close method:

private static <t extends closeable> void closeresource ( t  item ) {     try     {         if ( item != null )         {             item.close();         }     }     catch ( exception e )     {         throw new runtimeexception( e );     } } 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -