有什么方法来确定什么类型的类是Java中的一个实例? [英] Is there a way to determine what type a class is an instance of in Java?

查看:112
本文介绍了有什么方法来确定什么类型的类是Java中的一个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有3个类:

  class A {} 
class B extends A {}
class C extends A {}

然后可以确定特定对象是否 A B C ? / p>

我认为这样的东西可能工作:

  if .getClass()。isInstance(B.class)){
//为B
做某事} else(myObject.getClass()。isInstance(C.class)){
//为C
执行操作} else {
//为A
执行操作}

但是在阅读一点后,我认为它总是评价为B,因为它只是测试一个转换是否会工作,并且它们之间没有实质性的差异。

解决方案

这样做:

  if(myObject instanceof B){
//做一些B
} else(myObject instanceof C){
//为C
做一些事情} else {
//为A
做一些事情}


Say I have 3 classes like so:

class A {}
class B extends A {}
class C extends A {}

Would it then be possible to determine whether a particular object was an instance of A, B, or C?

I thought that something like this might work:

if (myObject.getClass().isInstance(B.class)) {
    // do something for B
} else (myObject.getClass().isInstance(C.class)) {
    // do something for C
} else {
    // do something for A
}

but after reading a little I think it would always evaluate as B since it's just testing if a cast would work and there's no substantial differences between them.

解决方案

Do this:

if (myObject instanceof B) {
    // do something for B
} else (myObject instanceof C) {
    // do something for C
} else {
    // do something for A
}

这篇关于有什么方法来确定什么类型的类是Java中的一个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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