如何获取值的类型(Java) [英] How to get the type of a value (Java)

查看:233
本文介绍了如何获取值的类型(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到的解决方案很有意义;如果知道变量的类型,那么就知道其值的类型。 Java就是这样。但是,如果我有一个像这样的继承类系统...

The solutions I've seen online make sense; if you know the type of the variable, then you know the type of its value. Java makes it that way; however, if I have a system of inherited classes such as this ...

DynastyPQ (base class)
FirstPQ (inherited class)

并以这种方式创建对象...

And create the objects in this manner ...

DynastyPQ pq = new FirstPQ();

有没有办法获取FirstPQ的类型,以便在强制转换中使用它,以便我可以访问类的专有方法?也许与此类似?

Is there a way to get the type of FirstPQ so that I can use it in a cast so that I can access the class's exclusive methods? Maybe something akin to this?

(typeof(pq's value)pq).exclusiveMethod()


推荐答案

您有一些选择。


  1. 您可以使用反射

  2. 您可以使用 instanceof

  3. 您可以使用访客模式

对于这些示例,我们将尝试查找此变量的类型:

For these examples, we will attempt to find the type of this variable:

Object obj = new TargetType();

我们想查看 obj 的类型为 TargetType

反射

您可以通过以下几种方式进行操作:

There are a couple ways you could do this:

if(obj == TargetType.class) {
    //do something
}

上面代码背后的想法是 getClass()返回对所使用的 Class 对象的引用实例化该对象。您可以比较引用。

The idea behind the code above is that getClass() returns a reference to the Class object used to instantiate that object. You can compare the reference.

if(TargetType.class.isInstance(obj)) {
    //do something
}

Class#isInstance 检查传递给方法的对象值是否是我们正在调用 isInstance 的类的实例。如果 obj 为空,它将返回 false ,因此不需要空检查。

Class#isInstance checks to see if the object value passed to method is an instance of the class we are calling isInstance on. It will return false if obj null, so no null check is needed. This requires casting to perform operations on the object.

instanceof

这很简单:

if(obj instanceof TargetType) {
    //do something
}

instanceof 是语言规范的一部分。如果 obj 为null,则返回 false 。这需要强制转换才能对对象执行操作。

instanceof is part of the language specification. This returns false if obj is null. This requires casting to perform operations on the object.

访问者模式

我已经在我的其他答案。您将负责处理 null 。您应该对模式进行更深入的研究,以了解它是否适​​合您的情况,因为这可能会过大。这不需要强制转换。

I have explained this in detail in one of my other answers. You would be in charge of handling null. You should look deeper into the pattern to see if it's right for your situation, as it could be an overkill. This does not require casting.

这篇关于如何获取值的类型(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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