我在使用状态模式时遇到问题,我不知道如何在State不使用的情况下检查 a是否属于某个实例instanceOf(因为这被认为是一种不好的做法)。
TCPConnection持有一个TCPState对象。假设我想获得所有TCPConnections具有 state 的TCPEstablished。我该怎么做?

一种方法是:
public List<TCPConnection> getAllEstablished() {
List<TCPConnection> list = new ArrayList<TCPConnection>();
for(TCPConnection tcp : allConnections) {
if(tcp.getState().instanceOf(TCPEstablished)) {
list.add(tcp);
}
}
return list;
}
Run Code Online (Sandbox Code Playgroud)
但这使用instanceOf,我宁愿不使用它。有没有更好的方法?还是我的使用instanceOf有效?
new.target所以我对Node 6.x 中添加的布尔值做了一些阅读。这是MDNnew.target上提供的一个简单示例
function Foo() {
if (!new.target) throw "Foo() must be called with new";
console.log("Foo instantiated with new");
}
Foo(); // throws "Foo() must be called with new"
new Foo(); // logs "Foo instantiated with new"
Run Code Online (Sandbox Code Playgroud)
但这读起来很像我目前使用下面的代码
var Foo = function (options) {
if (!(this instanceof Foo)) {
return new Foo(options);
}
// do stuff here
}
Run Code Online (Sandbox Code Playgroud)
new.target我的问题是:超过方法实例有什么好处吗?我并不认为这两者更清楚。new.target可能是 scosche 更容易阅读,但只是因为它少了一组括号()。
谁能提供我所缺少的见解?谢谢!
我有一个抽象类FooObject。只有两个孩子会继承FooObject,让我们称他们为ThisFooObject和ThatFooObject。
我正在寻找一种将 FooObject 变成任何子项的高性能方法。在这种情况下,这意味着不使用instanceof- 它以 <10% 的布尔查找速度执行。
我调查的方式是这样的:
import ThisObject from "./ThisObject";
import ThatObject from "./ThatObject";
abstract class FooObject {
isThisObject() : this is ThisFooObject {
// Either check for ThisFooObject properties, or override this
// in the ThisFooObject class to always return true.
return duckTypingTest();
}
// ditto here
isThatObject() : this is ThatFooObject {}
}
Run Code Online (Sandbox Code Playgroud)
我明白这并不漂亮。如果我有更多 FooObject 的孩子,这不是一种可扩展的方法 - 它要求父母以一种封装破坏的方式了解孩子。但在我的具体情况下,如果它避免我不得不做'instanceof',我愿意忍受这个。
从好的方面来说,当我有一个 FooObject 的引用,并且当它是一个 …
我有扩展父类的子类。假设我从 Child 类中创建了一个新实例“child”。当我检查条件时child instanceof Child,它返回false。但是,child instanceof Parent返回 true。
为什么会这样?
编辑
所以我发现这只发生在我用 Error 类扩展 Child 类时。让我留下下面的代码示例。
class Child extends Error {
constructor(message) {
super(message);
}
}
const ch = new Child();
console.log(ch instanceof Child);Run Code Online (Sandbox Code Playgroud)
第二次编辑
class PullCreditError extends Error {
public name: string;
public message: string;
public attemptsRemaining: number;
constructor(message: string, attemptsRemaining: number) {
super();
Error.captureStackTrace(this, PullCreditError);
this.name = 'PullCreditError';
this.message = message;
this.attemptsRemaining = attemptsRemaining;
}
}
Run Code Online (Sandbox Code Playgroud) 以下代码返回true.
console.log(document.createElement('script') instanceof Element);Run Code Online (Sandbox Code Playgroud)
在<iframe>上下文中执行相同的操作会返回false:
let iframe = document.querySelector('iframe');
iframe = iframe.contentDocument || iframe.contentWindow.document;
console.log(iframe.createElement('script') instanceof Element);
Run Code Online (Sandbox Code Playgroud)
这是为什么?
如何测试 val/var 是否属于预期类型?
我在 Kotlin 测试中缺少什么,例如:
value shouldBe instanceOf<ExpectedType>()
Run Code Online (Sandbox Code Playgroud)
这是我如何实施它:
inline fun <reified T> instanceOf(): Matcher<Any> {
return object : Matcher<Any> {
override fun test(value: Any) =
Result(value is T, "Expected an instance of type: ${T::class} \n Got: ${value::class}", "")
}
}
Run Code Online (Sandbox Code Playgroud) 我有这个内部类 Node,在 instanceof 检查时遇到这个奇怪的错误。我尝试用谷歌搜索,为什么会这样,但它只显示“不可转换类型”错误,而这不是。我还尝试将 Node 设为静态类,但这也没有帮助。我对此有点困惑,因此非常感谢您的帮助。提前致谢。
import java.util.Objects;
public abstract class Graph<E> {
protected class Node {
E item;
protected Node(final E item) {
this.item = item;
}
@Override
public boolean equals(final Object o) {
if (this == o)
return true;
else if(item == null)
return false;
else if(o instanceof final Node node) //error: "java: java.lang.Object cannot be safely cast to Graph<E>.Node"
return item.equals(node.item);
return item.equals(o);
}
@Override
public int hashCode() {
return Objects.hash(item);
}
}
}
Run Code Online (Sandbox Code Playgroud)
阅读一些答案后,我意识到我只犯了一个愚蠢的错误,该错误在这段代码中得到了纠正:
import java.util.Objects; …Run Code Online (Sandbox Code Playgroud) 我的代码在 java 17 上的 intellij 中运行,但在 java 14 上返回以下行的错误:
if (this.areas.get(i) instanceof Habitat area) {
返回错误:
java:instanceof中的模式匹配是预览功能,默认情况下处于禁用状态。
如何调整这一行以便它在 java 14 中工作?我知道我使用此功能的方式仅适用于 java 16+。
我有以下变量
MyObj myObj = new MyObj();
String myString = "myPackage.MyObj";
Run Code Online (Sandbox Code Playgroud)
其中MyObj这个样子
package myPackage;
class MyObj {
private String one;
private String two;
}
Run Code Online (Sandbox Code Playgroud)
如何检查是否myObj是字符串表示的完全限定类名的实例myString?
我班上有一个List界面类型.CriteriaQuery
List<Criteria> criteria = new ArrayList<Criteria>();
Run Code Online (Sandbox Code Playgroud)
我有几个具体的实现Criteria.我想给出Query一个遍历criteria列表的方法,并根据具体类型执行一些逻辑.
我现在这样做instanceof是这样的:
for(Criteria c : criteria) {
if(c instanceof ContextualCriteria){
// logic
}
...
}
Run Code Online (Sandbox Code Playgroud)
这是唯一/最好的方式吗?
instanceof ×10
java ×5
javascript ×3
inheritance ×2
oop ×2
typescript ×2
iframe ×1
kotlin ×1
kotlintest ×1
new-operator ×1
parent-child ×1
types ×1