How do you prevent unchecked cast warning when reading from ObjectInputStream?

K

Knute Johnson

How do you prevent unchecked cast warning when you read a parameterized
object from an ObjectInputStream? If TreeMap isn't parameterized then
this doesn't happen but that isn't really a good solution. Or should I
just ignore this?

The TreeMap in this case is TreeMap<String,Boolean>.

C:\>javac -Xlint:unchecked
com/knutejohnson/smallbook/sportsnetwork/TickerClient.java
com\knutejohnson\smallbook\sportsnetwork\TickerClient.java:390: warning:
[unchecked] unchecked cast found : java.lang.Object
required: java.util.TreeMap<java.lang.String,java.lang.Boolean>
map = (TreeMap<String,Boolean>)ois.readObject();
^
1 warning

Thanks,
 
T

Tom Hawtin

Knute said:
How do you prevent unchecked cast warning when you read a parameterized
object from an ObjectInputStream? If TreeMap isn't parameterized then
this doesn't happen but that isn't really a good solution. Or should I
just ignore this?

A common problem.

Write yourself a little utility method to read an object and cast. That
method can suppress the warnings "safely".

@SuppressWarnings("unchecked")
static <T> T readObject(
java.io_ObjectInputStream in
) throws java.io.IOException, java.lang.ClassNotFoundException {
return (T)in.readObject();
}

http://groups.google.com/group/comp.../thread/3c05ddbbe4eaaba4#doc_585daaa682e4e563

Tom Hawtin
 
K

Knute Johnson

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top