检测对象类型,然后进行相应的转换? [英] Detect Object type then cast it accordingly?

查看:132
本文介绍了检测对象类型,然后进行相应的转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



例如: binarySearch(Object o);



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



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



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



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

:)

解决方案

>


  1. 使用 instanceof 运算符。


  2. 在对象上调用 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 .compareTo 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:

  1. Use the instanceof operator.

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

这篇关于检测对象类型,然后进行相应的转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆