Java isInstance vs instanceOf operator

僤鯓⒐⒋嵵緔 提交于 2019-11-27 21:10:50
Dónal

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;
}

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

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

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);
}

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

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

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

Class.isInstance() doesn't work like your code expects. It tests whether the object you pass to it is an instance of the class. In you code:

expectedReturn.isInstance(SomeRelatedClass.class)

The object you're passing is a Class object. Try this instead, which returns true:

Class.class.isInstance(SomeRelatedClass.class);

What you're probably looking for is Class.isAssignableFrom(), e.g.:

Object.class.isAssignableFrom(Class.class);

Means you can do this:

Class klass = ...;
Object o = klass;

The expected argument of isInstance is an object that may be an Instance of the class that your class object represents. What you're comparing it to is an instance of the class... java.lang.Class! So it's not going to match.

e.g., would be true:

Class.class.isInstance(SomeRelatedClass.class);

Also would be true (without architectural commentary on the sanity of actually building your query helper this way)

expectedReturn.isInstance(new SomeRelatedClass());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!