Java isInstance vs instanceOf operator

后端 未结 3 1550
青春惊慌失措
青春惊慌失措 2020-12-05 18:19

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

Specificis? Ah well here\'s the gist:

enum QueryHelper {
  query1,
           


        
3条回答
  •  感情败类
    2020-12-05 18:39

    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;
    

提交回复
热议问题