I am writing a little class and I encountered a problem.
This class reads CSV file, there will be only one value for each key. I have
class CSVMap<T> extends AbstractMap<String,T>
and I have:
public void load(String filename)
{
try
{
BufferedReader out=new BufferedReader(new FileReader(filename));
String []tab;
T value;
while(out.ready());
{
tab=out.readLine().split(",");
}
} catch (IOException e)
{
e.printStackTrace();
}
}
now I need to create new instances of T to put them in my map ( I know that T has constructor that takes string).
I know about type-erasure in Java so only way out of this is a) passing T.Class to my load method or keeping it somewhere private in my class or b) keeping some private object T and using it in method to get Class object?
I am asking because I wanted to be sure if there isn't any other way to do it.
There is another way which you may wish to consider. That is getting your CSVMap to take as a parameter to its constructor an object which knows how to convert from from class to another class.
eg.
public class Test {
public static void main(String[] args) {
CSVMapLoader<Integer> loader = new CSVMapLoader<Integer>(new IntegerParser());
loader.load();
}
}
class CSVMapLoader<T> {
private final Parser<T> parser;
public Loader(Parser<T> parser) {
this.parser = parser;
}
public CSVMap<T> load() {
// as an example of how to get your T
T t = parser.parse("1000");
System.out.println("t equal to 1000? "+(t.equals(1000)));
// and instead put your real logic to load up map here
}
}
interface Parser<T> {
public T parse(String str);
}
class IntegerParser implements Parser<Integer> {
public Integer parse(String str) {
return Integer.valueOf(str);
}
}
As a side note of code design. You shouldn't really subclass (Abstract)Map in this case. What you want is class that knows how to load up key value pairs from a csv file. The Map interface is just about storing and accessing those pairs once loaded. So really you want a separate factory class that takes a file, parser and maybe base map type and loads up the map for you. Leaving you with an untouched map instance, unaware of how it was loaded.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With