测试类是否包含基于其名称的实例变量

有时我需要测试哪个类声明了一些变量,是否有另一种方法来测试它,如果具体类包含带有某个名称的变量

try { testLocalVariable = (String) (this.getClass().getDeclaredField("testVariable").get(this)); } catch (NoSuchFieldException ex) { } catch (SecurityException ex) { } catch (IllegalArgumentException ex) { } catch (IllegalAccessException ex) { } 

如果我理解正确,您可以在超类中使用此代码来测试子类是否具有testVariable字段。

为什么不简单地添加这样的方法?

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

对我来说似乎更多的OO,并没有打破封装。

那就是说,我真的不明白为什么你首先需要这个。

类具有字段,而不是局部变量。

您可以使用getDeclaredField()但是这不会找到超类声明的字段。

您不需要查找字段值,如果没有exception,则字段就在那里。