我有一堆傳感器,應該從超類繼承。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說:「不能在靜態上下文中使用它。」但是,我該如何糾正這個錯誤?
一方面,刪除靜態標籤將解決問題,另一方面,我必須在獲取我的屬性信息之前實例化每個傳感器。