java Instanceof判断一个对象的类型

instanceof 用来判断一个对象(Object)是否为某一个类型

比如String str = “abc”. str是否为String类型

HashMap m = new HashMap m 是否为一个hashmap
instanceof常用于,知道一个Object,但是后面的代码需要判断Object的类型。

package com.javaer.examples;
 
import java.util.HashMap;
 
public class TestInstance {
 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String str = "abc";
		HashMap m = new HashMap();
		Integer a =20;
		if( str instanceof java.lang.String){
			System.out.println("str is a String!");
		}
 
		if( m instanceof java.util.HashMap){
			System.out.println("m  is a HashMap!");
		}
 
		if( a instanceof java.lang.Integer){
			System.out.println("a  is a Integer!");
		}
	}
 
}


This entry was posted in JAVA and tagged . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/java-instanceof/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*