Nik*_*tel 292 java instanceof operators
我了解到Java有instanceof运营商.你能详细说明它的使用地点和优势吗?
Tho*_*mas 375
基本上,您检查对象是否是特定类的实例.当你有一个超类或接口类型的对象的引用或参数并且需要知道实际对象是否具有其他类型(通常更具体)时,通常使用它.
例:
public void doSomething(Number param) {
if( param instanceof Double) {
System.out.println("param is a Double");
}
else if( param instanceof Integer) {
System.out.println("param is an Integer");
}
if( param instanceof Comparable) {
//subclasses of Number like Double etc. implement Comparable
//other subclasses might not -> you could pass Number instances that don't implement that interface
System.out.println("param is comparable");
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果您经常使用该运算符,通常会暗示您的设计存在一些缺陷.因此,在设计良好的应用程序中,您应该尽可能少地使用该运算符(当然,该一般规则也有例外).
Jea*_*art 48
instanceof可用于确定对象的实际类型:
class A { }
class C extends A { }
class D extends A { }
public static void testInstance(){
A c = new C();
A d = new D();
Assert.assertTrue(c instanceof A && d instanceof A);
Assert.assertTrue(c instanceof C && d instanceof D);
Assert.assertFalse(c instanceof D);
Assert.assertFalse(d instanceof C);
}
Run Code Online (Sandbox Code Playgroud)
Bar*_*rth 27
instanceof是一个关键字,可用于测试对象是否为指定类型.
示例:
public class MainClass {
public static void main(String[] a) {
String s = "Hello";
int i = 0;
String g;
if (s instanceof java.lang.String) {
// This is going to be printed
System.out.println("s is a String");
}
if (i instanceof Integer) {
// This is going to be printed as autoboxing will happen (int -> Integer)
System.out.println("i is an Integer");
}
if (g instanceof java.lang.String) {
// This case is not going to happen because g is not initialized and
// therefore is null and instanceof returns false for null.
System.out.println("g is a String");
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的来源.
| 归档时间: |
|
| 查看次数: |
861174 次 |
| 最近记录: |