Check if a Class Object is subclass of another Class Object in Java

前端 未结 8 1011
鱼传尺愫
鱼传尺愫 2020-11-28 20:33

I\'m playing around with Java\'s reflection API and trying to handle some fields. Now I\'m stuck with identifying the type of my fields. Strings are easy, just do myFi

8条回答
  •  抹茶落季
    2020-11-28 21:12

    You want this method:

    boolean isList = List.class.isAssignableFrom(myClass);
    

    where in general, List (above) should be replaced with superclass and myClass should be replaced with subclass

    From the JavaDoc:

    Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter. It returns true if so; otherwise it returns false. If this Class object represents a primitive type, this method returns true if the specified Class parameter is exactly this Class object; otherwise it returns false.

    Reference:

    • Class.isAssignableFrom(Class)

    Related:

    a) Check if an Object is an instance of a Class or Interface (including subclasses) you know at compile time:

    boolean isInstance = someObject instanceof SomeTypeOrInterface;
    

    Example:

    assertTrue(Arrays.asList("a", "b", "c") instanceof List);
    

    b) Check if an Object is an instance of a Class or Interface (including subclasses) you only know at runtime:

    Class typeOrInterface = // acquire class somehow
    boolean isInstance = typeOrInterface.isInstance(someObject);
    

    Example:

    public boolean checkForType(Object candidate, Class type){
        return type.isInstance(candidate);
    }
    

提交回复
热议问题