I have a general Class called "Message":
public abstract class Message {
private int type;
private String origin;
private String destination;
public Message(int type, String origin, String destination) {
this.type = type;
this.origin = origin;
this.destination = destination;
}
public int getType() {
return type;
}
public String getOrigin() {
return origin;
}
public String getDestination() {
return destination;
}
}
Also I have 2 more classes that extend from that one. "Conffirmation Connection Message"
public class ConnectionConffirmationMessage extends Message{
public ConnectionConffirmationMessage(int type, String origin, String destination) {
super(type, origin, destination);
}
}
and "Connection Message"
public class ConnectionMessage extends Message{
User info;
public ConnectionMessage(int type, String origin, String destination, User info) {
super(type, origin, destination);
this.info = info;
}
public User getInfo() {
return info;
}
}
My problem is that now when I want to ask for the info when the Connection Message arrives I can’t. Because the general class "Message" doesn’t have the method "getInfo()".
Message msg = (Message) fin.readObject();
Any idea of what can I do?
Also, I can’t simply change the type because I have this in a while with a switch, so if another type of Message arrives I have to process it.
>Solution :
You can cast you message into the specific sub-type
Before Java 14
if (msg instanceof ConnectionMessage) {
User user = ((ConnectionMessage) message).getInfo();
// do something with the user
}
After Java 14
if (msg instanceof ConnectionMessage connectionMessage) {
User user = connectionMessage.getInfo();
// do something with the user
}
In this way, you will call the correct method.
Other solutions would be:
- adding an abstract method to your
Messageclass. There you could call method without casting. Disadvantage: You need to implement the abstract method to every subclass ofMessage. - using reflections and test for the existance of the
getInfoand call it via reflections. Generally speaking, you should not use reflections, if there is an native java way (like casting)