如何处理 "final fields may not have been initialized" 多个静态变量的问题?
How to deal with "final fields may not have been initialized" issue with multiple static variables?
在这段代码中,如果我将 'final' 添加到变量定义中,我将收到 "the final fields may have not been initialized" 错误。 Statckoverflow 上的一些建议解决方案倾向于为 return 值创建静态函数。但是,在这种情况下,我需要创建四个不同的函数来执行此操作。这个问题有没有更优雅的解决方案?
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();
}
}
However, in this case I need to create four different functions to do that.
由于您基本上在做同样的事情,但资源名称不同,因此一种方法就足够了:
private static String getResourceByName(string path) {
try {
return ClassPathResource(path).getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
现在您可以在初始化中使用相同的方法四次:
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");
在这段代码中,如果我将 'final' 添加到变量定义中,我将收到 "the final fields may have not been initialized" 错误。 Statckoverflow 上的一些建议解决方案倾向于为 return 值创建静态函数。但是,在这种情况下,我需要创建四个不同的函数来执行此操作。这个问题有没有更优雅的解决方案?
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();
}
}
However, in this case I need to create four different functions to do that.
由于您基本上在做同样的事情,但资源名称不同,因此一种方法就足够了:
private static String getResourceByName(string path) {
try {
return ClassPathResource(path).getFile().getAbsolutePath();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
现在您可以在初始化中使用相同的方法四次:
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");