我有一堆传感器,应该从超类继承。Java反射:从超类的继承类调用GetDeclaredFields()方法
在我的超类以及传感器本身中,存在静态的最终属性和我的属性的可能值范围,它们定义了我的传感器。
现在我想找出一个方法,该方法在超类中返回属性及其值范围的HashMap
。
由于事实上,传感器永远不会改变它的参数,我想用这个getAttributes()方法作为一个类方法,可选地在我的main []中调用它。
我的问题是:如何以静态方式获得属性(我此时使用了反射)如此好。我说的
UML图:
我的主要方法是这样的:
public static void main(String[] args){
HashMap<String, List<String>> a = SensorA.getConfigurationAttributes();
}
和我的抽象组件类:
public static HashMap<String, List<String>> getConfigurationAttributes(boolean getMandatoryOnly){
Field[] classAttributes = this.getClass().getDeclaredFields(); // error: cannot use this in static context
// ... other code, working with the attributes.
}
当然,现在, Java说:“不能在静态上下文中使用它。”但是,我该如何纠正这个错误?
一方面,删除静态标签将解决问题,另一方面,我必须在获取我的属性信息之前实例化每个传感器。