Java isInstance vs instanceOf运算符 [英] Java isInstance vs instanceOf operator

查看:173
本文介绍了Java isInstance vs instanceOf运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

整个泛型的东西有点像扔我一个循环,更多的是RTT。

The whole generics thing is kinda throwing me for a loop, and more so the RTT.

Specialis?好吧,这里是要点:

Specificis? Ah well here's the gist:

enum QueryHelper {
  query1,
  query2;
  static <T> QueryHelper getQueryHelper (Class<T> expectedReturn) {
    if (expectedReturn.isInstance (SomeRelatedClass.class))
      return query1;
    else
      return query2;
  }
}

然后我会这样称呼:

...
QueryHelper helper = QueryHelper.getQueryHelper(SomeRelatedClass.class);
...

这样我才能真正灵活地分配查询返回类型实际的帮手。它做了一些铸造和对象创建。我所看到的是,没有比赛,我应该以其他方式做到这一点吗?或者整个想法是不是很糟糕?

This is so that I can really flexibly assign the query return type in the actual helper. It does some casting and object creation. What I am seeing is that there is no match, should I be doing this some other way? Or is the whole idea just bad?

真正的核心是我不明白class.isInstance和instanceOf运算符之间的区别?我应该使用后者吗?

And the real heart of this is that I don't understand the difference between class.isInstance and the instanceOf operator? Should I be using the latter?

推荐答案


这样我才能真正灵活地在实际帮助器中分配查询返回类型。

This is so that I can really flexibly assign the query return type in the actual helper.

此方法的返回类型没有任何灵活性

There is nothing flexible about the return type of this method

static <T> QueryHelper getQueryHelper (Class<T> expectedReturn) {
    if (expectedReturn.isInstance (SomeRelatedClass.class))
      return query1;
    else
      return query2;
}

它将始终返回 QueryHelper的实例。如果您希望返回类型具有灵活性,则需要将其定义为:

It will always return an instance of QueryHelper. If you want the return type to be flexible you would need to define it as something like:

static <T> T getQueryHelper (Class<T> expectedReturn) {
}

现在返回类型很灵活,因为它将取决于参数的类型

Now the return type is flexible, because it will depend on the type of the argument


真正的核心是我不明白类之间的区别.isInstance和instanceOf运算符?

And the real heart of this is that I don't understand the difference between class.isInstance and the instanceOf operator?

不同之处在于instanceof执行在编译时修复的类型检查,例如:

The difference is that instanceof does a type-check that is fixed at compile-time, for example:

static boolean isInstance(Object myVar) {
    return (myVar instanceof Foo);
}

将始终检查myVar是否为Foo的实例,而

will always check that myVar is an instance of Foo, whereas

static <T> boolean isInstance(Object myVar, Class<T> expectedType) {
    return expectedType.isInstance(myVar);
}

将检查myVar是expectedType的实例,但expectedType可以是不同的每次调用方法时键入

will check that myVar is an instance of expectedType, but expectedType can be a different type each time the method is called

这篇关于Java isInstance vs instanceOf运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆