测试一个类是否包含基于其名称的实例变量 [英] Test if a class contains an instance variable based on its name
本文介绍了测试一个类是否包含基于其名称的实例变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有时我需要测试哪个类声明了一些变量,是否有另一种方法来测试它,如果具体类包含具有某个名称的变量
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;
}
对我来说似乎更面向对象,不会破坏封装.
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屋!
查看全文