下面的代码与IllegalArgumentException一起失败
public EnumSet<test> getData(){ // Line 1
return EnumSet.copyOf(get(test))) // Line 2
}
private Collection<Test> get(Test[] test){ //Line 1
test= test==null ? new Test[0] : test; // line 2
return Array.asList(test) //Line 3
}如果测试为null,那么get函数的第2行将创建测试和EnumSet.copyOf(get(test)) throws IllegalArgumentException的空数组
我不明白为什么会抛出这个异常?
发布于 2019-04-30 16:06:38
EnumSet使用一些反射来标识其元素的类型。(该集合使用“序数”的enum值来跟踪每个元素是否包括在内。)
当您使用EnumSet创建copyOf(Collection)时,它会检查集合是否是EnumSet。如果是,则使用与源集相同的类型。否则,它将尝试对源集合中的第一个元素调用getClass()。如果集合为空,则不存在第一个元素,也不需要查询其类。因此,在这种情况下,它会失败(“如果IllegalArgumentException不是EnumSet实例,并且不包含任何元素,则抛出EnumSet”)。
要创建一个空的EnumSet,您需要自己确定类,并使用。
Collection<Test> tests = get(test);
return tests.isEmpty() ? EnumSet.noneOf(Test.class) : EnumSet.copyOf(tests);https://stackoverflow.com/questions/55924784
复制相似问题