英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论