0

I want to make a general function which will fill a HashMap<String,TYPE extends GameObject> based on contend of a text file. It should work for any TYPE which implements methods getName() and fromString(). Currently, I found obstacle, that I cannot call constructor of TYPE.

The code:

public static <TYPE extends GameObject> void loadHashMap( Map<String,TYPE> mp, String filename ){
    BufferedReader reader = FileSystem.getReader( filename );
    String line;
    try{
        while( null != ( line = reader.readLine() )  ){
            TYPE item = new TYPE(); item.fromString( line ); // alternative 1
            // TYPE item = new TYPE( line );                 // alternative 2
            mp.put( item.getName(), item );
        };
    } catch (Exception e) { e.printStackTrace(); };
}

where GameObject is defined as:

public class GameObject {
    String name;
    public String getName(){ return name; };
    public void fromString( String s ){ name = s;   }
    public GameObject ( ){  } 
    public GameObject ( String s ){ name=name; }
}
Prokop Hapala
  • 2,424
  • 2
  • 30
  • 59

1 Answers1

1

In Java all template types are erased when compiling, so you are not supposed to do something like new TYPE(). You need to find another way to create an instance.

see Create instance of generic type in Java?

Community
  • 1
  • 1
hjhjw1991
  • 61
  • 5