Java中的instanceof运算符与isInstance方法
isInstance方法等效于instanceof运算符。如果在运行时使用反射创建对象,则使用该方法。一般做法是,如果要在运行时检查类型,请使用isInstance方法,否则可以使用instanceof运算符。请参阅下面的示例-
示例
public class Tester{
public static void main(String[] args) throws ClassNotFoundException {
Integer i = new Integer(10);
System.out.println(usingInstanceOf(i));
System.out.println(usingIsInstance(i));
}
public static String usingInstanceOf(Object i){
if(i instanceof String){
return "String";
}
if(i instanceof Integer){
return "Integer";
}
return null;
}
public static String usingIsInstance(Object i) throws ClassNotFoundException{
if(Class.forName("java.lang.String").isInstance(i)){
return "String";
}
if(Class.forName("java.lang.Integer").isInstance(i)){
return "Integer";
}
return null;
}
}输出结果
Integer Integer
热门推荐
8 孙媳妇祝福语简短
10 春节拜年祝福语儿童简短
11 分手快乐祝福语简短
12 牛年佛家祝福语大全简短
13 生日寿宴祝福语简短精辟
14 新婚红包祝福语简短男
15 新年留言老师祝福语简短
16 年底拜年祝福语大全简短
17 新年祝福语长辈简短红包
18 简短古文生日祝福语