我正在制作一个具有条形码扫描功能的 Android 应用程序,当我得到结果时,它作为 Barcode
的实例返回类(class)。对于这个问题,它有两个我感兴趣的值:barcode.format
和 barcode.valueFormat
这两个值都是整数,据我所知,这些整数基本上是(但不是)作为 Barcode 类定义中的静态字段的枚举。
因此,出于说明目的,您已经获得了 Barcode 的类定义,如下所示:
public class Barcode extends AbstractSafeParcelable {
...
public static final int ALL_FORMATS = 0;
public static final int CODE_128 = 1;
public static final int CODE_39 = 2;
public static final int CODE_93 = 4;
public static final int CODABAR = 8;
public static final int DATA_MATRIX = 16;
public static final int EAN_13 = 32;
public static final int EAN_8 = 64;
public static final int ITF = 128;
public static final int QR_CODE = 256;
public static final int UPC_A = 512;
public static final int UPC_E = 1024;
public static final int PDF417 = 2048;
public static final int AZTEC = 4096;
public static final int CONTACT_INFO = 1;
public static final int EMAIL = 2;
public static final int ISBN = 3;
public static final int PHONE = 4;
public static final int PRODUCT = 5;
public static final int SMS = 6;
public static final int TEXT = 7;
public static final int URL = 8;
public static final int WIFI = 9;
public static final int GEO = 10;
public static final int CALENDAR_EVENT = 11;
public static final int DRIVER_LICENSE = 12;
...
还有 barcode
实例可能返回 barcode.format
32 和一个 barcode.valueFormat
共 5 个。
所以在我这边,我想要的是让那些数字有一个字符串 'EAN_13 : PRODUCT'
,但一眼看去,这些public static final
字段不容易得到匹配的字符串值。
我当然可以做一个Map<int, string>
这里显示了所有已知类型,但我不喜欢这个想法,因为如果添加任何 future 格式,我的 Map
会过时的。我也不喜欢复制已经存在的信息。
那么如何在 Java 中以干净、面向 future 的方式将这些 int 转换为它们匹配的 String 值?
最佳答案
我做了一个小的 ans 简单示例,向您展示如何做到这一点。当然,我建议进行一些过滤(以防万一,在尝试解析之前确保它是一个 int),但这有点超出了这个 POC 的范围
public class Declared {
public static final int ONE = 1; // you can add any number of field here
public static final int TWO = 2; // it should still work. for private fields
// check the api to verify
public static void main(String[] args) throws Exception {
// get the fields in the Declared class, currently ONE and TWO
final Field[] declaredFields = Declared.class.getDeclaredFields();
Map<String, Integer> fields = new HashMap<>();
// add it field by field
for ( Field field : declaredFields ) {
fields.put(field.getName(), Integer.valueOf(field.getInt(null)));
}
// check the entryset for each element in your hashmap. it contains all you need
final Set<Map.Entry<String, Integer>> entries = fields.entrySet();
for ( Map.Entry<String, Integer> entry : entries ) {
System.out.println(entry.getKey() + " - > " + entry.getValue());
}
}
}
关于java - 从静态类成员转换为文本值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56541035/