Test if a class contains an instance variable based on its name

后端 未结 2 1177
渐次进展
渐次进展 2020-12-02 02:19

Sometimes I need to test which class has declared some variable(s), is there another way how to test that, if concrete class contains variable with some name



        
相关标签:
2条回答
  • 2020-12-02 02:41

    Classes have fields, not local variables.

    You can use getDeclaredField() however this will not find fields declared by super classes.

    You don't need lookup the fields value, if you don't get an exception the field is there.

    0 讨论(0)
  • 2020-12-02 02:44

    If I understand correctly, you use this code in a superclass to test if a subclass has a testVariable field.

    Why don't you simply add a method like this?

     /**
      * Returns true if the object declares a testVariable field, false otherwise. Subclasses should
      * override this method
      */
    protected boolean hasTestVariableField() {
        return false;
    }
    

    Seems much more OO to me, doesn't break encapsulation.

    That said, I've not really understood why you needed this in the first place.

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