I have this method:
private Message getMessage(DataInputStream in) throws IOException {
CommandEnum caption = CommandEnum.valueOf(in.readUTF());
BasicMessage inputMessage;
if (caption.equals(CommandEnum.BEGIN) || caption.equals(CommandEnum.FILEADDRESS)
|| caption.equals(CommandEnum.CONTAINNAMESERVER))
inputMessage = new Add开发者_Go百科ressMessage(caption,in.readUTF(),in.readInt());
if (caption.equals(CommandEnum.CONTAINFILE) || caption.equals(CommandEnum.DONTCONTAINFILE)
|| caption.equals(CommandEnum.WANTFILE))
inputMessage = new FileMessage(caption,in.readUTF());
else
inputMessage = new BasicMessage(caption);
in.readUTF();
return inputMessage;
}
The signature states that the method return Message
, an object I've created. Notice that in some cases it returns AddressMessage
, another object of mine that extends Message
.
My problem - in case i return new AddressMessage(arguments)
I can't downcast it later to
be an AddressMessage
object [writing (AddressMessage) object
]
I agree, if what you have is an AddressMessage, then it can be always be downcasted as such.
What I expect is more a logic mistake. That you actually try to downcast an instance of another class. Just try to debug that place or print obj.getClass()
just to verify what class you are actually trying to downcast.
You can also use if (my_message instanceof AddressMessage) ...
or something like this.
if (object.instanceOf(AddressMessage))... something like this? look here: Downcasting in Java
You should really use brackets in your if-else constructs, otherwise only the next statement is used as "then" clause, which can be confusing.
This is what your code looks like with brackets:
BasicMessage inputMessage;
if (SNIP1) {
inputMessage = new AddressMessage(caption,in.readUTF(),in.readInt());
}
if (SNIP2) {
inputMessage = new FileMessage(caption,in.readUTF());
} else {
inputMessage = new BasicMessage(caption);
}
in.readUTF();
return inputMessage;
you'll either get a FileMessage (SNIP2 = TRUE) or a BasicMessage (SNIP2 = FALSE), nothing else.
Edit: an "else if (SNIP2)" instead of "if (SNIP2)" will solve your problem, but you should really use brackets
精彩评论