【问题标题】:Java: Can you downcast with a variable?Java:你能用一个变量沮丧吗?
【发布时间】:2016-09-18 08:07:26
【问题描述】:

如果我有几个派生类的方法与基类不同,但彼此相似,我可以使用变量向下转换吗?

例如:

    Object derivedClass = baseClass.getChild().getClass();
    ((derivedClass)differentClassObj.differentClassMethod()).derivedClassMethod();

也许这太模糊和/或效率不高,因为我可以在基类中创建空方法来绕过这个问题(或其他我没有学过的技巧),但我仍然很好奇是否可以传递变量是否进入铸造。

感谢您的洞察!

编辑:为了进一步澄清任何混淆,我正在尝试确定是否可以使用变量进行转换。所以说我想将某些东西转换为字符串(只是为了论证):

    String myObjStr = MyObject.class.getSimpleName();
    // Then I want to know if I can cast objects using that variable in the casting 
    //(so far it doesn't appear to be working but I know that's because its a string. 
    //Is there some way I can manipulate it so that I CAN cast with it?)
    ((myObjStr).differentClassObj.differentClassMethod()).derivedClassMethod();

【问题讨论】:

  • 我不确定您在问什么,但您可以使用 reflection 来确定是否有任何实例具有可见的 derivedClassMethod() 和如果是,请调用它。

标签: java variables derived-class downcast


【解决方案1】:

虽然您可以使用 Class 对象来指定将对象转换为什么类型,但这并不能真正帮助您:

Class<? extends ParentClass> derivedClass = baseClassObject.getChild().getClass();

// The following kind of does the cast you want, but not in a useful way:
derivedClass.cast(differentClassObject)

问题是您仍然需要静态知道结果的类型。 cast 输出的静态类型仅与Class 对象的static 类型一样具体,而不是Class 对象实际代表的类。因此,即使您有一个代表ChildClassOnederivedClass 对象,您也只知道它是一个Class&lt;? extends ParentClass&gt;。虽然对象的cast 方法会为ChildClassTwo 的实例抛出异常,但您不能在返回值上调用ChildClassOne 方法。

如果这个类层次结构中的所有类实例都有您要查找的方法,但基类不能提供有用的实现,您应该标记基类抽象并将此方法作为抽象方法赋予它。如果此类层次结构中的某些对象没有您正在寻找的方法,您可能应该重新设计您的程序或以常规方式执行强制转换。引入接口可能是个好主意。无论如何,使用 Class 对象进行强制转换可能对您没有帮助。

【讨论】:

  • 好吧,听起来好像它不会达到我想要的效果,但这主要是出于我个人的好奇心,所以我感谢你花时间解释它。你给了我一些其他的东西来研究和探索。谢谢! :D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-27
  • 1970-01-01
  • 2016-07-07
相关资源
最近更新 更多