繁体   English   中英

根据名称测试 class 是否包含实例变量

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

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

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

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

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

您不需要查找字段值,如果您没有收到异常,则该字段就在那里。

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

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

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

对我来说似乎更面向对象,不会破坏封装。

也就是说,我并没有真正理解你为什么首先需要这个。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM