我正在尝试实现一个私人消息系统。让我知道这是否是糟糕的设计,但我有两个类User
和Recipient
. Recipient
是一个User
所以它继承User
。Recipient
具有附加属性,例如messageId
, readDate
, keepMessage
.
我的代码如下:
//This line gives me ClassCastException
recipient = (Recipient) user;
.
//GET id of user to send message to
String receiverId = request.getParameter("id");
//GET title of message
String title = request.getParameter("title");
//Get content of message
String content = request.getParameter("content");
//Retrieve logged in user from session
HttpSession session = request.getSession();
User sender = (User) session.getAttribute("user");
//Instantiate a new User to hold receiver
User user = new User();
//Retrieve object of user to send message to
UserService userService = new UserService();
user = userService.getUserById(Integer.valueOf(receiverId));
//Instantiate a new Recipient (extends User)
Recipient recipient = new Recipient();
//Cast User as a Recipient
recipient = (Recipient) user;
//Instantiate a message
Message message = new Message();
//message related stuff here....
//Pass the message content and Recipient to messageService
MessageService messageService = new MessageService();
messageService.sendPrivateMessage(message, recipient);