如果您的代码有“key = null;” 在 instanceof 测试之前,必然会抛出异常。
原因是 instancof 运算符检查所指向对象类型的引用,而不是它的声明方式。
您可以尝试使用这个简单的示例并相应地删除注释以查看差异:
public static void main(String[] args) {
//Object obj = new Integer(9);
Object obj = null;
if (!(obj instanceof Integer))
System.out.println("Not Integer.");
else
System.out.println("Is Integer");
}
此外,您可以在此处找到更多详细信息:
http://download.oracle.com/javase/tutorial/java/nutsandbolts/op2.html
希望能帮助到你 :)
Java泛型的完整示例:
class GenTest<Key extends Integer, Value>{
Key key;
Value val;
GenTest(Key key, Value val){
this.key = key;
this.val = val;
System.out.println("Key: " + key + " Value: " + val);
}
}
public class GenericRecap {
public static void main(String[] args) {
//Object obj = new Integer(9);
Object obj = null;
if (!(obj instanceof Integer))
System.out.println("Not Integer.");
else
System.out.println("Is Integer");
new GenTest<Integer, String>(9, "nine");
//new GenTest<String, String>("funny", "nine"); // In-Error
}
}
另请注意,通过使用“Key extends Integer”,如果您传递的不是 Integer 的子类,则会在运行时引发异常。此外,如果您正在使用检查它的 IDE,它将被标记为 GenTest 类的“类型不在界限内”。
Floats 和 Integer 都继承自 Number。因此,您可以“扩展 Number”,然后根据您想在代码中使用它的方式检查“instanceof Integer”或“instanceof Float”。
希望它有所帮助:) 干杯!