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
热门推荐
10 新人红包祝福语简短精辟
11 幼师给毕业祝福语简短
12 生日高考祝福语妹妹简短
13 下飞机祝福语简短英文
14 元宵发客户祝福语简短
15 爸妈金婚文案祝福语简短
16 新郎朋友红包祝福语简短
17 虎年五一祝福语大全简短
18 出阁宴祝福语姐姐简短