Java 为什么在使用Long而不是Integer时会得到ClassCastException?

Java 为什么在使用Long而不是Integer时会得到ClassCastException?,java,filesystems,classcastexception,Java,Filesystems,Classcastexception,基本上,我尝试了以下代码片段,得到了一个ClassCastException: public static void main (String []args) { Path path = Paths.get((System.getProperty("user.home")), "Desktop","usnumbers.txt"); try { Integer size = (Integer)Files.getAttribute(path, "bas

基本上,我尝试了以下代码片段,得到了一个ClassCastException:

public static void main (String []args)     
{
    Path path = Paths.get((System.getProperty("user.home")), "Desktop","usnumbers.txt");
    try {       
    Integer size = (Integer)Files.getAttribute(path, "basic:size", NOFOLLOW_LINKS);
    System.out.println("Size: " + size.toString());
    } catch (IOException e) {
    System.err.println(e);
    }
}
}
一旦我用
Long
更改关键字
Integer
,它就会得到修复。我检查了
Files.getAttribute(…)
的文档,它返回了一个不长的对象。此外,始终在同一页中,在解释此方法的用法时,他们实际上使用了整型关键字来强制转换对象。是oracle官方文档中解释它的链接。 直接从同一链接查看方法用法:

用法示例:假设我们需要 支持“unix”视图的系统:


Files.getAttribute
实际返回类型取决于属性,因此对于“unix:uid”,它返回
Integer
,但是对于“basic:size”,它返回
Long
。您不能将Long转换为Integer,反之亦然。

请尝试

Long size = (Long) Files.getAttribute(path, "basic:size", NOFOLLOW_LINKS);
System.out.println("Size: " + size);

不能使用强制转换来转换Java中的引用类型。这意味着,虽然可以将
long
转换为
int
,但不能将
long
转换为
Integer

类型转换失败,因为返回的属性值不是整数

getAttribute(…)
返回的属性的名称和类型在javadocs中为相应的类指定。在这种情况下,javadoc for声明
size
Long
而不是
整数

(这是有道理的,因为文件的大小可以大于
Integer.MAX\u VALUE


教训:不要只看例子。您还需要阅读并理解其余的文档

Long size = (Long) Files.getAttribute(path, "basic:size", NOFOLLOW_LINKS);
System.out.println("Size: " + size);