如何获取值的类型(Java)
我在网上看到的解决方案很有意义; 如果您知道变量的类型,那么您就知道它的值的类型。 Java就是这样做的; 但是,如果我有一个inheritance类的系统,比如这个……
DynastyPQ (base class) FirstPQ (inherited class)
并以这种方式创建对象……
DynastyPQ pq = new FirstPQ();
有没有办法获得FirstPQ的类型 ,以便我可以在演员表中使用它,以便我可以访问该类的独占方法? 也许类似于这个?
(typeof(pq's value)pq).exclusiveMethod()
你有几个选择。
- 你可以使用reflection
- 你可以使用
instanceof
- 您可以使用访客模式
对于这些示例,我们将尝试查找此变量的类型:
Object obj = new TargetType();
我们想看看obj
引用的obj
是否为TargetType
类型。
reflection
有几种方法可以做到这一点:
if(obj == TargetType.class) { //do something }
上面代码背后的想法是getClass()
返回对用于实例化该对象的Class
对象的引用。 您可以比较参考。
if(TargetType.class.isInstance(obj)) { //do something }
Class#isInstance
检查传递给method的对象值是否是我们调用isInstance
的类的实例。 如果obj
null,它将返回false
,因此不需要进行空检查。 这需要强制转换才能对对象执行操作。
的instanceof
这个很简单:
if(obj instanceof TargetType) { //do something }
instanceof
是语言规范的一部分。 如果obj
为null,则返回false
。 这需要强制转换才能对对象执行操作。
访客模式
我在其他一个答案中详细解释了这一点。 你将负责处理null
。 您应该深入了解模式,看看它是否适合您的情况,因为它可能是一种矫枉过正。 这不需要铸造。
尝试使用getClass()
方法。 这将返回特定对象的运行时类。 http://www.tutorialspoint.com/java/lang/object_getclass.htm
有几个选择:
-
使用
instanceof
运算符:-
if (pq instanceof FirstPQ) {((FirstPQ)pq).exclusiveMethod();}
-
-
使用
Class.isInstance(Object obj)
实例方法:-
FirstPQ firstPQ; if(pq.getClass().isInstance(firstPQ)) { firstPQ = (FirstPQ)pq; }
(注意:尚未测试。确认。 )
-
- 使用访客模式:
- 见Vince Emigh的回答 。