1

I have this code do load any serialized data:

public static <T> T loadData(String filename) {
        T o = null;
        try {
            FileInputStream fi = new FileInputStream(filename);
            ObjectInputStream oi = new ObjectInputStream(fi);
            o = (T) oi.readObject();
            oi.close();
            fi.close();
        } catch (Exception e) {}
        return o;
    }

I call it with this:

ArrayList<String> data = loadData("a.dat");

But in this file I have another serialized object (e.g. a java.util.File object). I expected a error at o = (T) oi.readObject();, which would be catched, but it crashes in the method call. Why?


EDIT: Okay problem solved with the following code:

public static <T> T loadData(Class<T> expectedClass, String filename) {
        T o = null;
        try {
            FileInputStream fi = new FileInputStream(filename);
            ObjectInputStream oi = new ObjectInputStream(fi);
            o = expectedClass.cast(oi.readObject());
            oi.close();
            fi.close();
        } catch (Exception e) {}
        return o;
    }
Flatron
  • 1,375
  • 2
  • 12
  • 33

1 Answers1

3

T is a generic type, and is "erased" at runtime. So at runtime, T is really just Object, and valid.

Only once you call it and try to coerce it to ArrayList<String> is the actual cast attempted, and fails.

Because of this, your IDE should be showing you an "unchecked" or "unsafe" warning on the cast to a generic type. (This line: o = (T) oi.readObject();)

See also: https://docs.oracle.com/javase/tutorial/java/generics/erasure.html

ziesemer
  • 27,712
  • 8
  • 86
  • 94