使用反射在 Java 中获取成员变量值的陷阱 [英] Pitfalls in getting member variable values in Java with reflection

查看:49
本文介绍了使用反射在 Java 中获取成员变量值的陷阱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,如下所示.我想获取成员变量的所有值.

I have an abstract class as follows. I want to get all the values of member variables.

public abstract class PARAMS {
    public static final String NAME1 = "VAL1";
    public static final String NAME2 = "VAL2";
    public static final String NAME3 = "VAL3";
}

使用反射检索值,如下所示.

The values are retrieved using reflection as follows.

Field[] fields = PARAMS.class.getFields();
for (Field field : fields) {
    String name = field.getName() ;
    String value = (String) field.get(name);
}

这是我第一次尝试反射.这是实现目标的正确方法吗?我想知道在这种情况下使用反射有哪些陷阱.

This is the first time I am experimenting with reflection. Is this a correct way to achieve the goal? I would like to know what are the pitfalls in using reflection in this case.

推荐答案

您的代码迭代静态和私有字段.所以你应该检查你是否只迭代静态字段.

You code iterates over both static and private fields. So you should check that you iterate over static fields only.

for (Field field : PARAMS.class.getFields()) {
    if (Modifiered.isStatic(field.getModifiers())) continue;
    String name = field.getName() ;
    String value = (String) field.get(PARAMS.class);
}

注意:正如 Jon 提到的,对于静态字段访问,实例参数被忽略.但是,我更喜欢传入类而不是 null,因为这是更好的缩进文档.

然而,更好的做法是用注释来注释你的字段,这样你只会得到那些你真的不希望其他程序员(甚至幕后的 Java 语言)添加其他静态字段的字段.如果你这样做,你的代码看起来像

It is however even better practice to annotate your fields with an annotation so that you only get those fields that you really want no other static fields added by other programmers (or even the Java language behind the scenes). If you do so, your code would look like

for (Field field : PARAMS.class.getFields()) {
    if (!field.isAnnotationsPresent(YourAnnotation.class)) continue;
    String name = field.getName() ;
    String value = (String) field.get(PARAMS.class);
}

这篇关于使用反射在 Java 中获取成员变量值的陷阱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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