我的方法将一个对象作为输入。
例如: 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).
更多推荐
检测对象类型,然后进行相应的转换?
发布评论