I'm reading in a couple of data files with methods like the readWeather method below (second code paragraph). The are two things separating these methods, one are the Class for the data, in the readWeather method the Class is WeatherData.
public final class WeatherData extends Data {
protected WeatherData(String[] dataLines, int lineIndex) {
super(dataLines, lineIndex);
}
}
/**
* Create and read new Data
*
* @param dataLines
* @param lineIndex
*/
protected Data(String[] dataLines, int lineIndex) {
super(createIdentifiableData(dataLines, lineIndex));
lineIndex += 4;
dataLinesIndex = readComponentData(dataLines, lineIndex);
}
protected Data() {
super();
}
And the second thing is the HashMap object which is used to store the data in. In this case weatherDataMap.
/**
* Read data
*
* @param path - datafile
*/
private void readWeather(String path) {
setupDataFileInfo(path);
final int nWeathers = Integer.parseInt(dataLines[lineIndex]);
weatherDataMap = new HashMap<>(calcHashMapSize(nWeathers));
for (int i = 0; i < nWeathers; i++) {
lineIndex++;
WeatherData data = new WeatherData(dataLines, lineIndex);
lineIndex = data.getLineIndex();
weatherDataMap.put(data.getId(), data);
}
}
Anyway I tried making a generic method in order to stop keeping to make new methods for different kind of data see method below (dataLines is a String[], lineIndex is an int). However I get an java.lang.NoSuchMethodException: GameData$WeatherData.([Ljava.lang.String;, int)
private <T extends Data> HashMap<Integer, T> readData(String className, HashMap<Integer, T> o, String path) {
setupDataFileInfo(path);
final int nDatas = Integer.parseInt(dataLines[lineIndex]);
o = new HashMap<>(calcHashMapSize(nDatas));
for (int i = 0; i < nDatas; i++) {
lineIndex++;
T data;
try {
data = (T) Class.forName(className).getDeclaredConstructor(String[].class, int.class)
.newInstance(dataLines, lineIndex);
lineIndex = data.getLineIndex();
o.put(data.getId(), data);
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException
| InvocationTargetException | NoSuchMethodException | SecurityException
| ClassNotFoundException e) {
e.printStackTrace();
}
}
return o;
}
I also get a "Type safety: Unchecked cast from capture#1-of ? to T" warning on the following line. I have looked at this question regarding the warning, but I don't understand why I get the warning in my code. why it is giving me no such method exception
data = (T) Class.forName(className).getDeclaredConstructor(String[].class, int.class)
.newInstance(dataLines, lineIndex);
Aucun commentaire:
Enregistrer un commentaire