检测对象类型,然后进行相应的转换?

编程入门 行业动态 更新时间:2024-10-12 03:25:52
本文介绍了检测对象类型,然后进行相应的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的方法将一个对象作为输入。

例如: binarySearch(Object o);

在binarySearch方法中,我需要一种方法来确定Object o的类型(或类)。然后我需要把它与那种类型。我会怎么做?

更具体地说,Object o是基类的子类(EG SalariedEmp是Employee的子类),我特别需要基类。

编辑:我想出了如何做我想要的,这真的应该是一个完全不同的问题。我需要使用 Comparable 中的pareTo方法来设置一种基于这些对象的私有数据比较两个对象的方法。所有我必须做的是使用 implements 关键字实现我的类作为'Comparable'。所以无论什么类型的对象在我的binarySearch方法中进行比较,如果它们是相同的(未知)类型,并且已实现Comparable,它的工作原理。这使我的binarySearch方法非常可重用于任何类型的可比类。

所以,公平地说,我会接受覆盖原始问题的答案。 / p>

:)

解决方案

>

  • 使用 instanceof 运算符。

  • 在对象上调用 getClass()(确保先检查null)。

  • My method takes as input an Object. How do i determine it's type, then cast it accordingly?

    So for example: binarySearch( Object o );

    Inside the binarySearch method, i need a way to determine the type (or class) of Object o. Then i need to cast it with that type. how would i do that???

    And more specifically, Object o is a child of a base class (EG SalariedEmp is child of Employee), and i specifically need the base class.

    EDIT: I figured out how to do what I wanted, which really should be a completely different question. I needed to use the pareTo method from Comparable to set up a way to compare two objects based on private data from those objects. All i had to do was implement my class as 'Comparable' using the implements keyword. So no matter what Type of objects are compared in my binarySearch method, it works if they are of the same (unknown) type and have Comparable implemented. This makes my binarySearch method very re-usable with any type of comparable class.

    So, in all fairness, I'll accept the answer that covers the original question.

    :)

    解决方案

    Two ways to do this:

  • Use the instanceof operator.

  • Call getClass() on the object (make sure to check for null first).

  • 更多推荐

    检测对象类型,然后进行相应的转换?

    本文发布于:2023-10-27 04:14:18,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1532279.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:对象   类型

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!