I'm trying to get the type Class
of a List<Student>
to be able to deserialize with the method Serialize#read
I have mounted which works but the IDE keeps warning me that the assignment is not safe, I want it to be.
Attempts to get the Class ofList<Student>
List<Student>.class // error de sintaxis
List.class // Es el único que me acepta y funciona.
Method to deserialize
public static <T extends Object> T read(final String fileName, final Class<T> clazz) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(fileName)));
final T data = clazz.cast(ois.readObject());
ois.close();
return data;
}
I inform you that there is no simple way to do what you want. As far as I've seen, you have two ways to do what you request:
Cast to generic and add the `@SuppressWarnings("unchecked") annotation. This just tells the compiler that the cast is safe at runtime. But we know that generics are removed at runtime, so this strategy only removes the compiler warning.
Create a method to cast the list. The method is simple:
Or done in Java 8 in a single line:
And you call your method: