Background
The existing system creates many HashMap instances through the Generics class:
import java.util.Map; import java.util.HashMap; public class Generics { public static <K,V> Map<K, V> newMap() { return new HashMap<K,V>(); } public static void main( String args[] ) { Map<String, String> map = newMap(); } }
This is the only point of creation for all instances of classes that implement the Map interface. We would like to change the map implementation without recompiling the application. This will allow us to use Trove THashMap , for example, to optimize the application.
Problem
Software may not be associated with Trove THashMap due to licensing terms. Thus, it would be great if there was a way to specify the name of the card to instantiate at runtime (for those people who do not have such licensing restrictions). For instance:
import java.util.Map; import java.util.HashMap; import gnu.trove.map.hash.THashMap; public class Generics { private String mapClassName = "java.util.HashMap"; @SuppressWarnings("unchecked") public <K,V> Map<K,V> newMap() { Map<K,V> map; try { Class<? extends Map<K,V>> c = (Class<Map<K,V>>)Class.forName( getMapClassName() ).asSubclass( Map.class ); map = c.newInstance(); } catch( Exception e ) { map = new HashMap<K,V>(); } return map; } protected String getMapClassName() { return this.mapClassName; } protected void setMapClassName( String s ) { this.mapClassName = s; } public static void main( String args[] ) { Generics g = new Generics(); Map<String, String> map = g.newMap(); System.out.printf( "Class = %s\n", map.getClass().toString() ); g.setMapClassName( "gnu.trove.map.hash.THashMap" ); map = g.newMap(); System.out.printf( "Class = %s\n", map.getClass().toString() ); } }
Question
Is there a way to avoid @SupressWarnings annotation when compiling with -Xlint and still avoid warnings?
source share