测试类是否包含基于其名称的实例变量 [英] Test if a class contains an instance variable based on its name

查看:107
本文介绍了测试类是否包含基于其名称的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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


推荐答案

如果我理解正确,测试一个子类是否有 testVariable 字段。

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;
}

看起来更多OO,不破坏封装。

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.

这篇关于测试类是否包含基于其名称的实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆