简体   繁体   English

基于对象实例进行类型转换的正确方法

[英]Proper way to type cast based on object instance

I have a very basic question which is more of a design question. 我有一个非常基本的问题,更多是设计问题。 Listed below are the classes where User is an abstract class. 下面列出的是其中User是抽象类的类。 Only PremiumUser and AdminUser can post messages whereas GuestUser can't post messages (hence there is no postedMessages; property in the GuestUser class). 只有PremiumUserAdminUser可以发布消息,而GuestUser不能发布消息(因此GuestUser类中没有发布消息属性)。

在此处输入图片说明

PROBLEM: I have a main class from where I call the postMessage() ; 问题:我有一个主类,从那里我可以调用postMessage() method but before calling this method I get the User object using another method (whose return type is User ). 方法,但是在调用此方法之前,我使用另一个方法(返回类型为User )获取User对象。 So, to call the postMessage() method, I will have to typecast the User object into either AdminUser or PremiumUser object. 因此,要调用postMessage()方法,我必须将User对象转换为AdminUserPremiumUser对象。 I see three ways to do that: 我看到三种方法可以做到这一点:

  1. Use the property userType in User class to make if-else comparison and typecast based on that. User类中使用属​​性userType进行if-else比较并基于此进行类型转换。
  2. Use java reflection to get method list for the object and call the postMessage method. 使用Java反射获取对象的方法列表,然后调用postMessage方法。
  3. Consider using an interface: I considered using an interface which will be implemented by AdminUser and PremiumUser class. 考虑使用接口:我考虑使用将由AdminUserPremiumUser类实现的接口。 Even in that case, I can't type cast the object of type User into the type interface and use it seamlessly to call postMessage(); 即使在那种情况下,我也无法将类型为User的对象类型转换为类型接口 ,并无缝使用它来调用postMessage();。

I was wondering if my design is deficient in some way or it is a common problem and there is a smarter solution for this. 我想知道我的设计是否存在某种缺陷,或者这是一个普遍的问题,并且对此有更智能的解决方案。

To safe cast you basically use something like: 为了安全地进行投射,您基本上可以使用以下方法:

PremiumUser.class.isAssignableFrom(object);

which also works for objects that inherit from PremiumUser (for example). 它也适用于从PremiumUser继承的对象(例如)。 There are multiple options to avoid this check but it is entirely a matter of design. 有多种选择可以避免这种检查,但这完全是设计问题。 Some examples: 一些例子:

  • Declare the postMessage() method in User class and implement it differently for each type of user. 在User类中声明postMessage()方法,并针对每种类型的用户以不同的方式实现它。
  • Implement Groups, Roles and Rights and check if the particular User has the right to post messages. 实现组,角色和权限,并检查特定用户是否有权发布消息。

Use an interface with the postMessage method in it: 将接口与postMessage方法一起使用:

interface HasPostMessage {
    boolean postMessage(String message);
}

Make PremiumUser and AdminUser implement it. 使PremiumUserAdminUser实现它。 Then: 然后:

if (user instanceOf HasPostMessage) {
    ((HasPostMessage) user).postMessage("The message");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM