Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long

Tags:

java

I created this simple example which is used to read Linux uptime:

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

Is there any other way to convert the result?

like image 623
user1285928 Avatar asked Oct 13 '14 10:10

user1285928


2 Answers

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 direct casting won't work.

like image 75
Konstantin Yovkov Avatar answered Oct 11 '22 14:10

Konstantin Yovkov


The problem appears to be in the following line:

long s = (long) Array.get(dic, 1);
  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.

  2. You can access the element of the array simply by dic[1] instead of Array.get(dic, 1)

Replace with the following code:

long s = Long.parseLong(dic[1]);
like image 42
Ansmat Avatar answered Oct 11 '22 14:10

Ansmat