Javadoc说String
工具 Comparable<String>
但是,下面的代码返回 false
:
String.class.isAssignableFrom(Comparable.class)
如何检查某个类是否实现了给定的接口(interface)?
最佳答案
你误解了什么isAssignableFrom(cls)
操作。引用 Javadoc:
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. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.
这意味着当你检查
String.class.isAssignableFrom(Comparable.class)
您实际上是在检查 String
类是否是 Comparable
类的父类(super class),而不是相反。你应该检查:
Comparable.class.isAssignableFrom(String.class)
关于java - 为什么 Java 的 String 不能从 Comparable 接口(interface)赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34492893/