我正在尝试实现私人消息系统。如果这是糟糕的设计,请告诉我,但我有两个课程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);
答案 0 :(得分:0)
除了您的类层次结构(这是另一个问题)之外,您还有多个语法问题。正如我所指出的那样,你将两次定义收件人变量,有两个不同的类。此外,您似乎正在尝试将用户转发给收件人,收件人将失败 - 收件人是用户,但用户不一定是收件人
答案 1 :(得分:0)
你无法用Java真正做到这一点。根据您上面所说的内容,您无法将收件人强制转换为用户。你真的需要这样做吗?在上面的实例中,看起来您应该能够将其实例化为收件人。
答案 2 :(得分:0)
您无法将超类强制转换为派生类。附加子类数据应该来自哪里?
答案 3 :(得分:0)
你不能用演员来做。最好的办法是向Recipient
添加一个带有User
参数的构造函数。然后就可以了
Recipient recipient = new Recipient(user);
或者更改sendPrivateMessage()
以接受User
而不是Recipient
。
答案 4 :(得分:0)
我认为做downcast是不好的,请检查你的班级层次结构。该对象实际上是一个子对象,您可以使用dynamic_cast