具有类名的Java instanceof [英] Java instanceof with class name

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

问题描述

我只是想问一个问题,也许这毫无意义。

I am just curious to ask this, maybe it is quite meaningless.

当我们在Java中使用instanceof时,例如:

When we are using instanceof in java, like:

if (a instanceof Parent){ //"Parent" here is a parent class of "a"
}

为什么我们不能像下面这样使用:

why we can't use like below:

if (a instanceof Parent.class){
}

第二个从严格的编程角度来看, instanceof是否更有意义? 父母和父母.class之间有什么区别?

Does the second 'instanceof' make more sense from the view of strict programming? What is the difference between "Parent" and "Parent.class"?

推荐答案


What is the difference between "Parent" and "Parent.class"?

后者是类文字-a访问类型为 Class< Parent> 的对象的方式。

The latter is a class literal - a way of accessing an object of type Class<Parent>.

前者只是类的名称,


第二种'instanceof'是否更有意义?严格编程的观点?

Does the second 'instanceof' make more sense from the view of strict programming?

不是因为语言定义了- instanceof only 使用类型名称,从不使用表达式。如果可以写

Well not as the language is defined - instanceof only works with the name of a type, never an expression. If you could write

if (a instanceof Parent.class)

然后我会期待您可以写:

Class<?> clazz = Parent.class;
if (a instanceof clazz)

...这不是它的工作方式。另一方面,您可以调用 Class.isInstance 方法。

... and that's just not the way it works. On the other hand, there is the Class.isInstance method which you can call if you want.

首先,严格编程的观点是什么意思?

What do you mean by "the view of strict programming" in the first place?

这篇关于具有类名的Java instanceof的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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