0

我正在尝试实现一个私人消息系统。让我知道这是否是糟糕的设计,但我有两个类UserRecipient. Recipient是一个User所以它继承UserRecipient具有附加属性,例如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);
4

5 回答 5

0

除了您的类层次结构(这是另一个问题)之外,您还有多个语法问题。正如我所指出的,您使用 2 个不同的类定义了两次接收者变量。此外,您似乎正在尝试将用户投射到收件人,这将失败 - 收件人是用户,但用户不一定是收件人

于 2012-04-13T18:48:21.953 回答
0

你不能用Java真正做到这一点。根据您上面所说的,您不能将收件人投射到用户。你真的需要这样做吗?在上面的实例中,您应该能够将其实例化为收件人。

于 2012-04-13T18:52:19.823 回答
0

您不能将超类强制转换为派生类。额外的子类数据应该从哪里来?

于 2012-04-13T18:56:20.297 回答
0

你不能用演员表来做到这一点。你最好的选择是添加一个构造函数来Recipient接受一个User参数。然后你可以做

Recipient recipient = new Recipient(user);

要么接受,要么sendPrivateMessage()接受 aUser而不是 a Recipient

于 2012-04-13T19:05:45.937 回答
0

我认为沮丧是不好的,请检查您的班级层次结构。如果该对象确实是子对象,则可以使用 dynamic_cast

于 2012-04-13T19:19:04.290 回答