Type safety Hashtable

Losnikov :

I am deserializing a Hashtable into a Hashtable instance using casting and i get this warning: Type safety: Unchecked cast from Object to Hashtable<Date,String>.

The code: list = ((Hashtable<Date,String>)oos.readObject());

Is there a way to solve this warning?

GhostCat salutes Monica C. :

Simple answer: no, there isn't.

You see, the signature of that method says: it returns Object:

public final Object readObject()

Thus you must cast here. And thus there is no other way than suppressing the warning.

And there is also no other way. Keep in mind: the idea is that you can write any kind of java object into such streams. And thus you can "pull" any kind of object from it, too. Thus Object is the only return type that makes sense here.

Of course, with Java generics, the result could be some T, or some T that is further restricted. But then that would still be compile time only, with zero guarantees that things turn out as expected at runtime.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=86125&siteId=1