Which of the following is better?

a instanceof B

or

B.class.isAssignableFrom(a.getClass())

The only difference that I know of is, when 'a' is null, the first returns false, while the second throws an exception. Other than that, do they always give the same result?

When using instanceof, you need to know the class of "B" at compile time. When using isAssignableFrom()it can be dynamic and change during runtime.

2013年10月28日13分10秒

instanceof can only be used with reference types, not primitive types. isAssignableFrom() can be used with any class objects:

a instanceof int  // syntax error
3 instanceof Foo // syntax error
int.class.isAssignableFrom(int.class) // true

See http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class).

2013年10月28日13分10秒

Talking in terms of performance :

class A{}
class B extends A{} A b = new B(); void execute(){
boolean test = A.class.isAssignableFrom(b.getClass());
// boolean test = A.class.isInstance(b);
// boolean test = b instanceof A;
} @Test
public void testPerf() {
// Warmup the code
for (int i = 0; i < 100; ++i)
execute(); // Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
execute();
}
final long elapsed = System.nanoTime() - start;
System.out.println(count+" iterations took " + TimeUnit.NANOSECONDS.toMillis(elapsed) + "ms.);
}

It gives :

  • A.class.isAssignableFrom(b.getClass()) : 100000 iterations took 15ms
  • A.class.isInstance(b) : 100000 iterations took 12ms
  • b instanceof A : 100000 iterations took 6ms

So that we can conclude instanceof is faster !

2013年10月28日13分10秒

A more direct equivalent to a instanceof B is

B.class.isInstance(a)

This works (returns false) when a is null too.

2013年10月27日13分10秒

Apart from basic differences mentioned above, there is a core subtle difference between instanceof operator and isAssignableFrom method in Class.

Read instanceof as “is this (the left part) the instance of this or any subclass of this (the right part)” and readx.getClass().isAssignableFrom(Y.class) as “Can I write X x = new Y()”. In other words, instanceof operator checks if the left object is same or subclass of right class, while isAssignableFrom checks if we can assign object of the parameter class (from) to the reference of the class on which the method is called. Note that both of these consider the actual instance not the reference type.

Consider an example of 3 classes A, B and C where C extends B and B extends A.

B b = new C();

System.out.println(b instanceof A); //is b (which is actually class C object) instance of A, yes. This will return true.
System.out.println(b instanceof B); // is b (which is actually class C object) instance of B, yes. This will return true.
System.out.println(b instanceof C); // is b (which is actually class C object) instance of C, yes. This will return true. If the first statement would be B b = new B(), this would have been false.
System.out.println(b.getClass().isAssignableFrom(A.class));//Can I write C c = new A(), no. So this is false.
System.out.println(b.getClass().isAssignableFrom(B.class)); //Can I write C c = new B(), no. So this is false.
System.out.println(b.getClass().isAssignableFrom(C.class)); //Can I write C c = new C(), Yes. So this is true.

2013年10月27日13分10秒

There is also another difference:

null instanceof X is false no matter what X is

null.getClass().isAssignableFrom(X) will throw a NullPointerException

2013年10月28日13分10秒

There is yet another difference. If the type (Class) to test against is dynamic, e.g. passed as a method parameter, then instanceof won't cut it for you.

boolean test(Class clazz) {
return (this instanceof clazz); // clazz cannot be resolved to a type.
}

but you can do:

boolean test(Class clazz) {
return (clazz.isAssignableFrom(this.getClass())); // okidoki
}

Oops, I see this answer is already covered. Maybe this example is helpful to someone.

2013年10月28日13分10秒

This thread provided me some insight into how instanceof differed from isAssignableFrom, so I thought I'd share something of my own.

I have found that using isAssignableFrom to be the only (probably not the only, but possibly the easiest) way to ask one's self if a reference of one class can take instances of another, when one has instances of neither class to do the comparison.

Hence, I didn't find using the instanceof operator to compare assignability to be a good idea when all I had were classes, unless I contemplated creating an instance from one of the classes; I thought this would be sloppy.

2013年10月28日13分10秒

Consider following situation. Suppose you want to check whether type A is a super class of the type of obj, you can go either

... A.class.isAssignableFrom(obj.getClass()) ...

OR

... obj instanceof A ...

But the isAssignableFrom solution requires that the type of obj be visible here. If this is not the case (e.g., the type of obj might be of a private inner class), this option is out. However, the instanceof solution would always work.

2013年10月27日13分10秒

some tests we did in our team show that A.class.isAssignableFrom(B.getClass()) works faster than B instanceof A. this can be very useful if you need to check this on large number of elements.

2013年10月28日13分10秒

instanceof cannot be used with primitive types or generic types either. As in the following code:

//Define Class< T > type ...

Object e = new Object();

if(e instanceof T) {
// Do something.
}

The error is: Cannot perform instanceof check against type parameter T. Use it's erasure Obect instead since further generic type information will be erased at runtime.

Does not compile due to type erasure removing the runtime reference. However, the code below will compile:

if( type.isAssignableFrom(e.getClass())){
// Do something.
}

2013年10月27日13分10秒

判断一个类是否为另一个类的实例 instanceof关键字和isAssignableFrom方法的区别的更多相关文章

  1. 阶段1 语言基础+高级_1-3-Java语言高级_06-File类与IO流_05 IO字符流_5_flush方法和close方法的区别

    flush之后,还可以继续使用流写文件

  2. 在动态sql的使用where时,if标签判断中,如果实体类中的某一个属性是String类型,那么就可以这样来判断连接语句:

    在动态sql的使用where时,if标签判断中,如果实体类中的某一个属性是String类型,那么就可以这样来判断连接语句: 如果是String类型的字符串进行判空的时候: <if test=&q ...

  3. instanceof关键字用于判断一个引用类型变量所指向的对象是否是一个类(或接口、抽象类、父类)的实例。

    http://lavasoft.blog.51cto.com/62575/79864/    深入Java关键字instanceof 2008-06-02 07:50:43 标签:Java 关键字 休 ...

  4. 苹果公司的新的编程语言 Swift 高级语言(十一)--初始化类的析构函数的一个实例

    一 .实例的初始化          实例的初始化是准备一个类.结构或枚举的实例以便使用的过程. 初始化包含设置一个实例的每个存储属性为一个初始值,以及运行不论什么其他新的实例可以使用之前须要的设置或 ...

  5. WinSock IOCP 模型总结(附一个带缓存池的IOCP类)

    前言 本文配套代码:https://github.com/TTGuoying/IOCPServer 由于篇幅原因,本文假设你已经熟悉了利用Socket进行TCP/IP编程的基本原理,并且也熟练的掌握了 ...

  6. C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值

    转自goldeneyezhang原文 C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值 C#利用反射,遍历获得一个类的所有属性名,以及该类的实例的所有属性的值总结: 对应某个类的 ...

  7. 一个封装比较完整的FTP类——clsFTP

    前几天,看见园子里面的博友写了一个支持断点续传的FTP类,一时技痒,干脆写了个更完整的clsFtp类.只是我写这个clsFtp不是支持断点续传的目的,而是为了封装FTP几个基本常用的操作接口. 功能 ...

  8. 手写一个HTTP框架:两个类实现基本的IoC功能

    jsoncat: 仿 Spring Boot 但不同于 Spring Boot 的一个轻量级的 HTTP 框架 国庆节的时候,我就已经把 jsoncat 的 IoC 功能给写了,具体可以看这篇文章&l ...

  9. 一个名为不安全的类Unsafe

    最近为了更加深入了解NIO的实现原理,学习NIO的源码时,遇到了一个问题.即在WindowsSelectorImpl中的 pollWrapper属性,当我点进去查看它的PollArrayWrapper ...

随机推荐

  1. vue 开发系列(一) vue 开发环境搭建

    概要 目前前端开发技术越来越像后台开发了,有一站式的解决方案. 1.JS包的依赖管理像MAVEN. 2.JS代码编译打包. 3.组件式的开发. vue 是一个前端的一站式的前端解决方案,从项目的初始化 ...

  2. vue中的路由独享守卫的理解

    1.vue中路由独享守卫意思就是对这个路由有一个单独的守卫,因为他的守卫方式于其他的凡是不太同 独享守卫于前置守卫使用方法大致是一样的 在路由配置的时候进行配置, { path:'/login', c ...

  3. mysql学习之路_事物_存储过程_备份

    数据备份与还原 备份:将当前已有的数据保留. 还原:将已经保留的数据恢复到对应表中 为什么要做数据备份 1,防止数据丢失,被盗,误操作 2,保护数据记录 数据备份还原方式有多种:数据表备份 单表数据备 ...

  4. 基础运动move.js

    /* * 事件绑定 */ function myAddEvent(obj,ev,fn){ if(obj.attachEvent){ obj.attachEvent('on' + ev,fn); }el ...

  5. day25(令牌机制)

    令牌机制 作用:处理页面重复提交,造成数据多次写入数据库. 使用方法: 类似于验证码机制,使用session记录一个不可能重复的值(Uuid)在访问controller时对session进行校验. / ...

  6. php实现网站四则运算。

    1.设计思路: 在index.php中建立两个表单,有两个提交,一个跳转到fourArithmeticOperation.php,这里保存用户输入的参数到config.txt中,留给main函数调出. ...

  7. poj 2488 A Knight's Journey

    题目 题意:给出一个国际棋盘的大小 p*q,判断马能否不重复的走过所有格,并记录下其中按字典序排列的第一种路径. 因为要求字典序输出最小,所以按下图是搜索的次序搜素出来的就是最小的. 初始方向数组:i ...

  8. [kuangbin]树链剖分A - Aragorn's Story

    比较水的题了,比模板题还要简单一点 理解了这个结构,自己打出来的,但是小错误还是很多,越来越熟练吧希望 错误函数updata,updata_lca,query||错误地方区间往下递归的时候是left ...

  9. Android-Java-等待唤醒机制原理

    儿时的游戏:(等待 与 唤醒) 有一群小朋友一起玩一个游戏,这个游戏可能大家都玩过,大家一起划拳,划拳输得最惨的那个小朋友去抓人(这个小朋友取名为 CPU),被抓的很多人取名为线程,有很多线程,如果其 ...

  10. 2015年 10月最新苹果IOS上架App Store商店步骤

    1.1.前期工作 首先你需要有一个苹果的开发者帐号,一个Mac系统. 如果没有帐号可以在打开http://developer.apple.com/申请加入苹果的开发者计划.支付99美元每年,怎么申请网 ...