Java Reflection:从超类继承的类中调用GetDeclaredFields()方法

时间:2013-12-20 13:22:19

标签: java reflection

我有一堆传感器,应该从超类继承。

在我的超类中,以及在传感器本身中,我的属性有静态最终属性和可能的​​值范围,它定义了我的传感器。

现在我想找出一个方法,该方法返回一个HashMap个属性及其值在超类中的范围。

由于传感器永远不会更改其参数,我想使用此getAttributes()方法作为类方法,可选地在我的main []中调用它。

我的问题是:如何以静态方式获取属性(我现在使用了反射)那么好。

我所说的UML图:
Here

我的主要方法如下:

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说:“不能在静态环境中使用它。”但是我该如何纠正这个错误?

一方面,删除静态标记可以解决问题,但另一方面,我必须在获取属性信息之前实例化每个传感器。

2 个答案:

答案 0 :(得分:0)

您正在使用关键字“this”,它在静态方法中引用该对象的实例。 这是不正确的。

为了完成相同的任务,请改用此代码:

Field[] fields = Class.forName("my.package.MyClass").getDeclaredFields();

答案 1 :(得分:0)

如果您将要检索这些字段的类作为方法的参数传递,则可以静态地执行此操作。

否则你只能为你所在的班级做这件事,因为你已经知道了所有宣称的领域,所以这种做法会失败。

静态方法不是继承的,所以你不能在子类上神奇地调用它(为此你确实需要删除static修饰符)。

因此,做这样的事情可能会达到你想要的目的:

public static HashMap<String, List<String>> getConfigurationAttributes(boolean getMandatoryOnly, Class c) 
{
     Field[] classAttributes = c.getDeclaredFields();
     // ... other code, working with the attributes.
} 

编辑:现在关于反思的强制警告:使用这样的反射不是一个非常好或优雅的解决方案。反思代价高昂,适用于许多语言功能,而不是一种非常简洁的实现方式。请尽量避免反思,大多数情况下都有简单,优雅和简单的解决方案。

相关问题