如何通过反射获取并初始化字段?

huangapple go评论79阅读模式
英文:

How to get and initialize field through reflection?

问题

我有一个名为ColorConstants的类,其中包含一些静态字段:

public class ColorConstants {
    public static final Color BLACK;
    public static final Color BLUE;
    public static final Color GREEN;
    public static final Color RED;
    // ....
}

我想要检查一个给定的颜色(String)是否存在于该类中。

使用反射是否是适当的方法?

String s = "RED";
Field f = ColorConstants.class.getField(s);
Color colorConstant = (Color) myField.get(null);

在这里,我不确定如何获取实际的值。
因此,我基本上需要的是:要么ColorConstant.RED(如果存在),要么null(如果不存在)。

PS:ColorConstants不是我自己的类,我只是与它一起工作。所以我不能将其结构更改为枚举。

英文:

I have a class ColorConstants with some static fields:

public class ColorConstants {
    public static final Color BLACK;
    public static final Color BLUE;
    public static final Color GREEN;
    public static final Color RED;
    // ....
}

I want to check if a given color (String) exists in that class.

Is using reflections the appropriate way?

String s = "RED";
Field f = ColorConstants.class.getField(s);
Color colorConstant = (Color) myField.get(null);

Here I'm not sure how to get the actual value.
So what I basically need is: either ColorConstant.RED (if exists) or null (if doesn't exist).

PS: ColorConstants is not my own class, I just work with it. So I can't change its structure to an enum.

答案1

得分: 1

首先,您需要按名称获取Field对象,就像您已经做过的那样,接下来您可以通过捕获NoSuchFieldException来测试字段是否存在:

Color colorConstant = null;
String s = "RED";
try {
  Field f = ColorConstants.class.getField(s);
  colorConstant = f.get(null);
} catch (NoSuchFieldException e){
  // 在这里无需处理,colorConstant已经是null
}
return colorConstant;
英文:

First, you need to get the Field object by name as you already did, next you can test field existance by catching NoSuchFieldException:

Color colorConstant = null;
String s = "RED";
try {
  Field f = ColorConstants.class.getField(s);
  colorConstant = f.get(null);
} catch (NoSuchFieldException e){
  // Nothing to do here colorConstant already null
}
return colorConstant;

huangapple
  • 本文由 发表于 2020年10月7日 21:12:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64244755.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定