在下面的示例中(来自我的coursepack),我们希望为Square实例c1提供一些其他对象的引用p1,但前提是这两个对象是兼容的类型.
if (p1 instanceof Square) {c1 = (Square) p1;}
Run Code Online (Sandbox Code Playgroud)
我在这里不明白的是,我们首先检查p1确实是一个Square,然后我们仍然施展它.如果是Square,为什么演员?
我怀疑答案在于明显和实际类型之间的区别,但我仍然感到困惑......
编辑:
编译器将如何处理:
if (p1 instanceof Square) {c1 = p1;}
Run Code Online (Sandbox Code Playgroud)
Edit2:
问题是instanceof检查实际类型而不是表观类型?然后演员改变了表观类型?
谢谢,
JDelage
这种方法能true以某种方式返回吗?
public static <T> boolean isVoid(T t)
{
return t instanceof Void;
}
Run Code Online (Sandbox Code Playgroud) 考虑这样一个带有原型链的对象:
var A = {};
var B = Object.create(A);
var C = Object.create(B);
Run Code Online (Sandbox Code Playgroud)
如果C在其原型链中有A,如何检查运行时?
instanceof 不合适,因为它的设计与构造函数一起使用,我在这里没有使用它.
我重写了equals()方法,我需要知道对象是否是Event的子类的实例(Event是超类).我想要像"obj subclassof Event"这样的东西.怎么做到这一点?
提前致谢!
我需要一个方法,我可以传递一个参数,我假设它是一个类(不确定),在该方法中,instanceof将用于检查x是否是传递的类的实例.
我该怎么做?我尝试了一些但没有用的东西.
在我的应用程序中,我有一个2d实体数组来表示网格.网格中的每个位置都可以为空或由实体占用(在这种情况下,它只是一个人或墙).现在我instanceof用来检查一个实体是一个人还是一堵墙.
我正在考虑为每个实体提供一个方法,该方法返回一个enum说明其类型的方法,即墙实体将返回EntityType.WALL.我想知道这是否是最好的想法,删除使用instanceof或instanceof适合在这种情况下?
我在变量中有一个异常(没有抛出).
什么是最好的选择?
Exception exception = someObj.getExcp();
try {
throw exception;
} catch (ExceptionExample1 e) {
e.getSomeCustomViolations();
} catch (ExceptionExample2 e) {
e.getSomeOtherCustomViolations();
}
Run Code Online (Sandbox Code Playgroud)
要么
Exception exception = someObj.getExcp();
if (exception instanceof ExceptionExample1) {
exception.getSomeCustomViolations();
} else if (exception instanceof ExceptionExample2) {
exception.getSomeOtherCustomViolations();
}
Run Code Online (Sandbox Code Playgroud) 可以if( .. instanceof ...), elseif(... instanceof ...), ... 用开关替换块吗?
例如:
<?php
$class = ..... //some class
if($class instanceof SomeClass) {
//do something
} elseif($class instanceof SomeAnotherClass) {
//do something else
}
Run Code Online (Sandbox Code Playgroud) 可能重复:
Java:Instanceof和Generics
我正在尝试编写一个将通用List转换为特定类型List的函数.找到下面的代码
public <T>List<T> castCollection(List srcList, Class<T> clas){
List<T> list =new ArrayList<T>();
for (Object obj : srcList) {
if(obj instanceof T){
...
}
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
但obj instanceof T显示编译错误 -
无法对类型参数T执行instanceof检查.请改为使用其擦除对象>,因为将在运行时擦除其他泛型类型信息.
任何澄清或获得预期结果的方法?
提前致谢.:)
如何在Kotlin中找到变量类型?在Java中有instanceof,但Kotlin不存在:
val properties = System.getProperties() // Which type?
Run Code Online (Sandbox Code Playgroud) instanceof ×10
java ×7
generics ×2
dynamic ×1
enums ×1
equals ×1
exception ×1
javascript ×1
kotlin ×1
performance ×1
php ×1
polymorphism ×1
subclass ×1
throws ×1
typeerror ×1
void ×1