在我的应用程序中,我使用类似以下内容的内容
if($val instanceof Carbon)
...
Run Code Online (Sandbox Code Playgroud)
不幸的是,除非我之前在代码中使用Carbon(即使只是Carbon::now();),否则它总是返回 false。为什么?
为了验证类成员身份,in和instanceof关键字的行为似乎相同。那么两者有什么区别呢?有什么区别吗?StackOverflow 上有几个问题(此处或此处),其中给出了两个关键字作为此目的的解决方案,但没有提及两者之间的区别或何时使用一个关键字更合适。另外,官方文档提到该关键字in相当于调用对象的isCase()方法,但没有详细说明该instanceof关键字的作用。
这两个关键字在类继承和接口实现方面的行为似乎相同:
class MyMap extends LinkedHashMap { }
def foo = new LinkedHashMap()
def bar = new MyMap()
println("LinkedHashMap instance is 'in' LinkedHashMap: ${foo in LinkedHashMap}")
println("LinkedHashMap instance is 'instanceof' LinkedHashMap: ${foo instanceof LinkedHashMap}")
println("LinkedHashMap instance is 'in' Map: ${foo in Map}")
println("LinkedHashMap instance is 'instanceof' Map: ${foo instanceof Map}")
println("MyMap instance is 'in' LinkedHashMap: ${bar in LinkedHashMap}")
println("MyMap instance is 'instanceof' …Run Code Online (Sandbox Code Playgroud) 当 Java 执行自动装箱时,为什么这是编译时错误?我错过了什么吗?
int primitiveIntVariable = 0;
if (primitiveIntVariable instanceof Integer) {
}
Run Code Online (Sandbox Code Playgroud)
我得到
Inconvertible types; cannot cast 'int' to 'java.lang.Integer'
Run Code Online (Sandbox Code Playgroud) 以下打字稿片段在严格模式下重现(编译器)问题,编译后的代码运行良好:
class ClassX
{
constructor(public label: string) {}
}
class ClassA extends ClassX
{
constructor() { super('A'); }
}
class ClassB extends ClassX
{
constructor() { super('B'); }
}
type TClass = ClassA | ClassB;
class Wrapper<T extends TClass>
{
constructor(public source: TClass)
{
if(Wrapper.IsB(this)) console.log(this.source.label);
// Works normally:
// if(source instanceof ClassA) this.Log();
// else if(source instanceof ClassB) this.Log();
if(Wrapper.IsA(this)) console.log(this.source.label);
// this results in 'never', would emit error TS2339 without the type guard
else if(Wrapper.IsB(this)) console.log((this as Wrapper<ClassB>).source.label); …Run Code Online (Sandbox Code Playgroud) 为什么该isInstanceOf[T]方法不能按预期工作?
在下面,我定义了一个hello类和伴生对象。在hello对象中,我this.isInstanceOf[T]在代码行“ hel.typetest[Int]”中进行测试,true类型T为时怎么会出现这种情况Int?
object hello {
def main(args: Array[String]): Unit = {
Console.println("main")
val hel = new hello
hel.typetest[Int]
}
}
class hello {
def typetest[T: ClassTag]: Unit = {
Console.println(this.isInstanceOf[T])
Console.println(this.getClass)
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
main
true
class hello
Run Code Online (Sandbox Code Playgroud) 假设我们有一个动物流。
我们有不同的动物子类,并且我们希望在流上应用过滤器以仅包含流中的斑马。我们现在仍然有动物流,但只包含斑马。为了获得斑马流,我们仍然需要进行投射。
Stream<Zebra> zebraStream = animalStream
.filter(Zebra.class::isInstance)
.map(Zebra.class::cast);
Run Code Online (Sandbox Code Playgroud)
Java 14 引入了instanceof 的模式匹配,所以我们现在可以使用:
if (animal instanceof Zebra zebra) {
System.out.println(zebra.countStripes());
}
Run Code Online (Sandbox Code Playgroud)
有没有办法在流管道中使用模式匹配?当然你可以这样做:
Stream<Zebra> zebraStream = animalStream.map(animal -> {
if (animal instanceof Zebra zebra) {
return zebra;
}
return null;
})
.filter(Objects::nonNull);
Run Code Online (Sandbox Code Playgroud)
但恕我直言,这真的很难看。
I have Java 19, and I am attempting to do some simple pattern-matching on a record that I created. However, Java is giving me a very confusing compilation error. Here is the simplest example I could make that causes the error.
public class ExpressionTypeIsASubsetOfPatternType
{
public record Triple(int a, int b, int c) {}
public static void main(String[] args)
{
System.out.println("Java Version = " + System.getProperty("java.version"));
final Triple input = new Triple(1, 2, 3);
if (input instanceof Triple t)
{ …Run Code Online (Sandbox Code Playgroud) 我可以在instanceof表达式中使用基本类型文字或类型变量吗?
class MyClass<T> {
{
boolean b1 = null instanceof T; // T erasure -> Object should be used
boolean b2 = 2 instanceof Integer; // Incompatible operands
}
Run Code Online (Sandbox Code Playgroud)
我收到了编译错误.有没有办法绕过这些错误并在instanceof表达式中使用原始类型的文字/类型变量?
基本上,我想要放心,不,我永远无法做到这一点.
我正在研究一个JavaScript应用程序并且遇到了这种奇怪的行为.
任何人都可以向我解释原因
function BaseClass() {}
function ClassOne() { this.bar = "foo"; }
function ClassTwo() { this.foo = "bar"; }
var base = new BaseClass();
ClassOne.prototype = base;
ClassTwo.prototype = base;
var one = new ClassOne();
var two = new ClassTwo();
one instanceof ClassTwo && two instanceof ClassOne;
// The line above will return true, but i think it should return false,
// because obviously one is not an instance of ClassTwo!
Run Code Online (Sandbox Code Playgroud) 是否有一个可以与instanceof运算符一起使用的有效类Type变量?例如:
String s = "abc";
Class<?> classType = String.class;
if (s instanceof classType) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
作为替代方案:
if (s.getClass() == classType) {
//do something
}
Run Code Online (Sandbox Code Playgroud)
是否会有任何性能优势?
instanceof ×10
java ×5
autoboxing ×1
function ×1
generics ×1
groovy ×1
java-record ×1
java-stream ×1
javascript ×1
laravel ×1
new-operator ×1
php ×1
php-carbon ×1
predicate ×1
prototype ×1
reflection ×1
scala ×1
type-erasure ×1
types ×1
typescript ×1