有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java如何从另一个类中提取字段的值

我试图从另一个只读类获取所有字段和值,并将它们写入一个文件,如何获取字段的值

该类是只读的,没有getter:

  public class colorConstants {
    public static final String BLUE = "blue";
    public static final String RED = "red";
    public static final String YELLOW = "yellow";
    ...
    
    public colorConstants() {}
  }

在另一类中:

Field[] fields = colorConstants.class.getFields();
for(Field : fields) {
  String fieldName = fieldName;
  
  //how to get the value of each field
  String value = fieldName.get()?
}

共 (1) 个答案

  1. # 1 楼答案

    你可以这样做:

    import java.lang.reflect.Field;
    
    import static java.lang.reflect.Modifier.STATIC;
    
    public class Example {
        public static class colorConstants {
            public static final String BLUE = "blue";
            public static final String RED = "red";
            public static final String YELLOW = "yellow";
            public String blah;
    
            public colorConstants() {}
        }
    
        public static void main(String[] args) throws IllegalAccessException {
            Field[] fields = colorConstants.class.getFields();
            for (Field field : fields) {
    
                if ((field.getModifiers() & STATIC) != 0) {
                    String value = (String) field.get(null);
                    System.out.println(value);
                } else {
                    System.out.println("Ignoring non-static field " + field.getName());
                }
            }
        }
    }
    
    

    我改进了样式,将colorConstants改为ColorConstants,因为类名应该以大写字母开头,并将Field改为field