英文:
Why is java.util.Set not Assignable From java.lang.Iterable?
问题
当我调用Set.class.isAssignableFrom(Iterable.class)
时,它返回false
。
然而,在文档中,java.util.Set
被列为java.lang.Iterable
的子接口。因此我感到困惑。你甚至可以尝试在一行代码中测试:
System.out.println(Set.class.getName() + " is " + ((Set.class.isAssignableFrom(Iterable.class)) ? "" : "NOT ") + "assignable from " + Iterable.class.getName());
它会打印出java.util.Set is NOT assignable from java.lang.Iterable
。
为什么会这样呢?
英文:
When I call Set.class.isAssignableFrom(Iterable.class)
, it returns false
.
Nevertheless, in the docs, java.util.Set
is listed as a subinterface of java.lang.Iterable
. Hence my confusion. You can even try it out in a single line of code:
System.out.println(Set.class.getName() + " is " + ((Set.class.isAssignableFrom(Iterable.class)) ? "" : "NOT " ) + "assignable from " + Iterable.class.getName());
it prints java.util.Set is NOT assignable from java.lang.Iterable
.
Why is that?
答案1
得分: 3
因为你错误地使用了 isAssignableFrom
。
正如文档所述,isAssignableFrom(Class<?> cls)
"确定由此Class对象表示的类或接口是否与指定的Class参数表示的类或接口相同,或者是指定的Class参数的超类或超接口"。所以 cls
应该是 Set.class
,完整的语法是:
Iterable.class.isAssignableFrom(Set.class)
。
...确实会返回 true
。
英文:
That's because you're using isAssignableFrom
wrong.
As the docs say, isAssignableFrom(Class<?> cls)
"determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter". So cls
would be Set.class, and the full syntax would be:
Iterable.class.isAssignableFrom(Set.class)
.
...which, indeed, returns true
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论