How to find out if a field is instanceof a type via reflection?

后端 未结 4 1168
不知归路
不知归路 2020-12-24 04:32

I want to find out via reflection if a field is an instance of some type T.

Lets say I have an object o. Now I want to know if it has any

相关标签:
4条回答
  • 2020-12-24 05:11

    The rather baroquely-named Class.isAssignableFrom is what you're after. I usually end up having to read the javadoc to make sure I get it the right way around:

    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.

    Specifically, this method tests whether the type represented by the specified Class parameter can be converted to the type represented by this Class object via an identity conversion or via a widening reference conversion.

    For example:

    public class X {
        
       public int i;
    
       public static void main(String[] args) throws Exception {
          Class<?> myType = Integer.class;
          Object o = new X();
          
          for (Field field : o.getClass().getFields()) {
             if (field.getType().isAssignableFrom(myType)) {
                System.out.println("Field " + field + " is assignable from type " + o.getClass());
             }
          }
       }
    }
    
    0 讨论(0)
  • 2020-12-24 05:25

    In case of NullPointerException, you can use org.springframework.util.TypeUtils#isAssignable(java.lang.reflect.Type, java.lang.reflect.Type) instead of java.lang.Class#isAssignableFrom

    0 讨论(0)
  • 2020-12-24 05:27

    You have to use isAssignableFrom.

    0 讨论(0)
  • 2020-12-24 05:29

    If you want to compare the field type of a custom class you should try this, use .class because only primitive types has .TYPE.

    if(field.getType().isAssignableFrom(**YOURCLASS.class**)){}

    0 讨论(0)
提交回复
热议问题