标签: instanceof

在 Java 中使用 instanceof 运算符

我有一个叫做基类class Base和两个子类

class A extends Base
Run Code Online (Sandbox Code Playgroud)

class B extends Base
Run Code Online (Sandbox Code Playgroud)

fooBase.

而不是把实现fooin class Aand class B,这样我就可以做

void foo (Object o)
{
    // A's implementation
    assert o instanceof A;     
}


 void foo (Object o)
 {
     // B's implementation
     assert o instanceof B; 
 }
Run Code Online (Sandbox Code Playgroud)

无论如何要放入fooBase,并且仍然可以检查运行时类吗?我想过这样的事情:

 void foo (Object o)
 {
    // Check that o is instanceof a runtime class
    assert o instanceof this.getClass(); // ????
 }
Run Code Online (Sandbox Code Playgroud)

谢谢。

java runtime class instanceof

2
推荐指数
1
解决办法
3266
查看次数

原则 2. 查询生成器。关联实例类型

我使用 Doctrine 2 Query Builder 对 DQL 有以下请求,效果很好:

$qb->select('post')
    ->from('Posts\Entity\Post','post')
    ->join('post.author','author')
    ->where('author INSTANCE OF :utype')
    ->setParameter('utype',$userType);
Run Code Online (Sandbox Code Playgroud)

但是,考虑到这个例子反映了大型查询的一部分,我想摆脱这个join。我试过这个:

$qb->select('post')
    ->from('Posts\Entity\Post','post')        
    ->where('post.author INSTANCE OF :utype')
    ->setParameter('utype',$userType);
Run Code Online (Sandbox Code Playgroud)

但它不起作用。

我怎样才能避免使用join?或者也许还有其他方法来优化此类查询?

谢谢

instanceof dql doctrine-orm

2
推荐指数
1
解决办法
3773
查看次数

避免强制转换和instanceOf

我有一个界面

public interface Details {
   // nothing needed until now
}
Run Code Online (Sandbox Code Playgroud)

它在如下类中使用:

public class Value {
    // many fields
    private Details details;

    public Value(SomeType type) {
        switch (type) {
        case TYPE_1:
        case TYPE_2:
            this.details = new DetailsA();
            break;
        case TYPE_3:
            this.details = new DetailsB();
            break;
        default:
            throw new NotImplementedException("not yet implemented");
        }
    }

    public Details getDetails() {
        return this.details;
    }
}
Run Code Online (Sandbox Code Playgroud)

该接口有两个实现

public class DetailsA implements Details {

    private BigDecimal betragA;

    public DetailsA() {
    }

    public BigDecimal getBetragA() {
      return …
Run Code Online (Sandbox Code Playgroud)

java design-patterns casting instanceof

2
推荐指数
1
解决办法
1725
查看次数

Laravel 5.5 $exception instanceof AuthenticationException 未按预期工作

伙计们。我是 Laravel 的新手。刚刚安装了 5.5 并尝试在App\Exceptions\Handler中捕获 AuthenticationException,如下所示

public function render($request, Exception $exception)
{
    if ($exception instanceof AuthenticationException) {
        //Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是 ($exception instanceof AuthenticationException) 总是返回 false。

dd($exception instanceof AuthenticationException) //return false.
Run Code Online (Sandbox Code Playgroud)

当我 dd($exception) 时我得到了

AuthenticationException{
    #gurad...
    ....
    .....
}
Run Code Online (Sandbox Code Playgroud)

然后我尝试

get_class($exception) return \Illuminate\Auth\AuthenticationException
Run Code Online (Sandbox Code Playgroud)

然而,

dd($exception instanceof Exception) //return true.
Run Code Online (Sandbox Code Playgroud)

请帮忙。谢谢。

php authentication exception instanceof laravel

2
推荐指数
1
解决办法
5056
查看次数

如何理解类型`new(... args:any [])=> any`

我正在阅读类验证器库的代码,它具有以下isInstance方法:

/**
 * Checks if the value is an instance of the specified object.
 */
isInstance(object: any, targetTypeConstructor: new (...args: any[]) => any) {
    return targetTypeConstructor
        && typeof targetTypeConstructor === "function"
        && object instanceof targetTypeConstructor;
}
Run Code Online (Sandbox Code Playgroud)

关于如何去理解类型有new (...args: any[]) => any什么想法吗?这是我第一次看到这种构造...

javascript validation instanceof typescript

2
推荐指数
2
解决办法
442
查看次数

为什么 TypeScript 中的 instanceof 不适用于继承类?

我有以下课程:

class ApiError extends Error {
    httpCode: number
    constructor(message:string, httpCode:number = 400) {
        super(message);
        this.httpCode = httpCode;
    }
}

export class ErrorForbidden extends ApiError {
    constructor(message:string = 'Forbidden') {
        super(message, 403);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我创建一个实例,如下所示:

const error = new ErrorForbidden();
console.info(error instanceof ErrorForbidden); // false
console.info(error instanceof Error); // true
Run Code Online (Sandbox Code Playgroud)

因此,它似乎检测到它是 的实例,Error但不是 的实例,ErrorForbidden即使这就是我创建它的方式。

知道为什么它不起作用吗?以及如何让它发挥作用?

instanceof typescript

2
推荐指数
1
解决办法
2888
查看次数

如何使用 Typescript 检查数组中泛型的实例

我有一个接收数组的函数,但它们可以是不同的类型。根据我需要不同格式的类型:

public format(value: Foo[] | Bar[]) {
  // this does not work
  if (value instanceof Foo[]) ...
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以用来instanceof检查 Typescript 中是否有某个类的对象。

new Foo() instanceof Foo // true
Run Code Online (Sandbox Code Playgroud)

这也适用于检查我是否有数组。

new Array<Foo> instanceof Array // true
Run Code Online (Sandbox Code Playgroud)

但我无法检查我的数组是否实际上被输入到 Foo

new Array<Foo>() instanceof Array<Foo> 
// The right-hand side of an 'instanceof' expression must be of type 'any' 
// or of a type assignable to the 'Function' interface type.
Run Code Online (Sandbox Code Playgroud)

有没有办法显式检查数组值的类型?

arrays instanceof typescript

2
推荐指数
1
解决办法
1万
查看次数

Dart 中的运行时类型检查 - 检查列表

我想检查请求的响应是否http与特定的datatype(= List<dynamic) 匹配。

case 200:
    var responseJson = json.decode(response.body);

    print(responseJson['results'].runtimeType);  // Output: I/flutter (13862): List<dynamic>
    print(responseJson['results'].runtimeType is List<dynamic>);  // Output: I/flutter (13862): false

    if (responseJson['results'].runtimeType is List<dynamic> &&
        responseJson['results'].length > 0) {
      return responseJson;
    }
    throw NotFoundException('Result is empty...');
Run Code Online (Sandbox Code Playgroud)

我很困惑...为什么会打印出来falseruntimType显示的输出List<dynamic>应该是true......

types dynamic instanceof dart

2
推荐指数
1
解决办法
2034
查看次数

在instanceof方法中使用Class&lt;?&gt;参数

我有以下方法可以返回不同类型的可存储(例如:食物,矿石)。

库存.java

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(cls.isInstance(storable)) {
            this.inventory.remove(storable);
            return storable;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

它有效,但是我被迫将结果投射如下:

Food food = (Food) inventory.get(Food.class);
Run Code Online (Sandbox Code Playgroud)

instanceof对于 Java 15 及更高版本,我们可以直接使用(链接到 javadoc )定义强制转换对象。我想知道是否可以使用这个新语法并直接返回强制转换的对象。

我尝试了这个,但instanceof关键字仅适用于类型而不是变量:

public Storable get(Class<? extends Storable> cls) {
    for (Storable storable : inventory) {
        if(storable instanceof cls castedItem) {  //cls cannot be resolved to a type
            this.inventory.remove(storable);
            return castedItem;
        }
    }
    return null;
}
Run Code Online (Sandbox Code Playgroud)

java casting instanceof java-15

2
推荐指数
1
解决办法
470
查看次数

instanceof运算符不使用类类型变量

我有条件 -

public class A {}
public class B extends A {}
A a = new B();



boolean flag = a instanceof B; // returns true

public boolean isOfType(A a, Class<? extends A> type) {
    return (a instanceof type); // throws syntax error
}
Run Code Online (Sandbox Code Playgroud)

我很好奇为什么这个条件会引发语法错误.我在这里做错了吗?

java class instanceof

1
推荐指数
1
解决办法
1715
查看次数