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; }
}
0

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.