java.lang.ClassCastException: java.lang.String 不能转换为 java.lang.Long
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26338361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
提问by user1285928
I created this simple example which is used to read Linux uptime:
我创建了这个用于读取 Linux 正常运行时间的简单示例:
public String getMachineUptime() throws IOException {
String[] dic = readData().split(" ");
long s = (long) Array.get(dic, 1);
return calculateTime(s);
}
private String readData() throws IOException {
byte[] fileBytes;
File myFile = new File("/proc/uptime");
if (myFile.exists()) {
try {
fileBytes = Files.readAllBytes(myFile.toPath());
} catch (java.nio.file.AccessDeniedException e) {
return null;
}
if (fileBytes.length > 0) {
return new String(fileBytes);
}
}
return null;
}
private String calculateTime(long seconds) {
int day = (int) TimeUnit.SECONDS.toDays(seconds);
long hours = TimeUnit.SECONDS.toHours(seconds)
- TimeUnit.DAYS.toHours(day);
long minute = TimeUnit.SECONDS.toMinutes(seconds)
- TimeUnit.DAYS.toMinutes(day)
- TimeUnit.HOURS.toMinutes(hours);
long second = TimeUnit.SECONDS.toSeconds(seconds)
- TimeUnit.DAYS.toSeconds(day)
- TimeUnit.HOURS.toSeconds(hours)
- TimeUnit.MINUTES.toSeconds(minute);
return "Day " + day + " Hour " + hours + " Minute " + minute
+ " Seconds " + second;
}
When I run the code I get this exception:
当我运行代码时,出现此异常:
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
java.lang.ClassCastException: java.lang.String 不能转换为 java.lang.Long
Is there any other way to convert the result?
有没有其他方法可以转换结果?
回答by Konstantin Yovkov
I believe you have to replace
我相信你必须更换
long s = (long) Array.get(dic, 1);
with
和
long s = Long.valueOf((String) Array.get(dic, 1));
or even better:
甚至更好:
long s = Long.valueOf(dic[1]);
The reason is that your array consists of String
object, and directcasting won't work.
原因是您的数组由String
对象组成,直接转换不起作用。
回答by Ansmat
The problem appears to be in the following line:
问题似乎出在以下行中:
long s = (long) Array.get(dic, 1);
The get(Object array, int index) method of java.lang.reflect.Array returns an instance of Object, which cannot be directly cast to long.
You can access the element of the array simply by dic[1] instead of Array.get(dic, 1)
java.lang.reflect.Array 的 get(Object array, int index) 方法返回一个 Object 的实例,不能直接转换为 long。
您可以简单地通过 dic[1] 而不是 Array.get(dic, 1) 访问数组的元素
Replace with the following code:
替换为以下代码:
long s = Long.parseLong(dic[1]);