Reputation: 7633
In this code, if I add 'final' to the variable definitions, I will receive "the final fields may have not been initialized" error. Some suggested solutions on Statckoverflow tend to be creating static functions to return the value. However, in this case I need to create four different functions to do that. Is there a more elegant solution to this issue?
private static String MODEL_PATH;
private static String VECTORS_PATH;
private static String NEG_PATH;
private static String POS_PATH;
static {
try {
MODEL_PATH = new ClassPathResource("models/word2vec_model").getFile().getAbsolutePath();
VECTORS_PATH = new ClassPathResource("models/model.zip").getFile().getAbsolutePath();
NEG_PATH = new ClassPathResource("models/neg.txt").getFile().getAbsolutePath();
POS_PATH = new ClassPathResource("models/pos.txt").getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 2
Views: 171
Reputation: 726569
However, in this case I need to create four different functions to do that.
Since you are doing essentially the same thing, but with different resource names, one method would be sufficient:
private static String getResourceByName(string path) {
try {
return ClassPathResource(path).getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
Now you can use the same method four times in your initialization:
private static final String MODEL_PATH = getResourceByName("models/word2vec_model");
private static final String VECTORS_PATH = getResourceByName("models/model.zip");
private static final String NEG_PATH = getResourceByName("models/neg.txt");
private static final String POS_PATH = getResourceByName("models/pos.txt");
Upvotes: 2