Gettin枚举类型可能不会被实例化异常 [英] Gettin enum types may not be instantiated Exception
本文介绍了Gettin枚举类型可能不会被实例化异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在获得RuntimeException
I am getting RuntimeException
枚举类型可能未被实例化
Enum types may not be instantiated
我不知道为什么。我想要的是用一个整数值来识别一年,因为我有9,所以其他方法的年份是2006.代码:
I don't know why. What I want is to identify a year by an integer value like i have 9 so the year for other Methods is 2006. Code:
public class P21Make {
enum Catalog {
year2005(9),year2006(12),year2007(15),year2008(18),
year2009(21),year2010(23),year2011(25),year2012(28),
year2013(31),year2014(33),year2015(36),year2016(39),
year2017(42),year2018(45),year2019(48),year2020(51);
private int id;
Catalog(int c){
this.id=c;
}
}
public P21Make() {
Catalog c = new Catalog(9); // The Exception
}
}
推荐答案
你不能像这样实例化枚举。你有2个可能性
You cannot instantiate enum like this . You have 2 possiblities
1.Catalog c = Catalog.year2005;
2。通过添加可以根据代码(整数值)返回您的枚举的方法,在您的枚举中进行以下更改。例如
2. Make the following change in your enum by adding a method that can return you enum based on code(integer value) . E.g.
enum Catalog {
year2005(9),year2006(12),year2007(15),year2008(18),
year2009(21),year2010(23),year2011(25),year2012(28),
year2013(31),year2014(33),year2015(36),year2016(39),
year2017(42),year2018(45),year2019(48),year2020(51);
private int id;
Catalog(int c){
this.id=c;
}
static Map<Integer, Catalog> map = new HashMap<>();
static {
for (Catalog catalog : Catalog.values()) {
map.put(catalog.id, catalog);
}
}
public static Catalog getByCode(int code) {
return map.get(code);
}
}
然后分配像这样
Catalog c = Catalog.getByCode(9);
这篇关于Gettin枚举类型可能不会被实例化异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文