Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java反射类型转换数组_Java_Reflection_Properties - Fatal编程技术网

Java反射类型转换数组

Java反射类型转换数组,java,reflection,properties,Java,Reflection,Properties,我将实体类Config字段中的信息作为键/值对存储在属性文件中 fieldName1 = fieldValue1 fieldName2 = fieldValue2 ... 直到现在我才硬编码 Properties props = new Properties(); props.setProperty("pathToExe", config.getPathToExe()); // ... Writer writer = new OutputStreamWriter(new File

我将实体类
Config
字段中的信息作为键/值对存储在
属性文件中

fieldName1 = fieldValue1  
fieldName2 = fieldValue2  
...  
直到现在我才硬编码

Properties props = new Properties();
props.setProperty("pathToExe", config.getPathToExe()); 
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.ISO_8859_1);
props.store(writer, "");
writer.close(); 
但由于我想不断扩展这些特性,我一直在考虑将其动态化。
Config
具有类型为
String
String[]
int
的字段
我读过Java中的反射,但不熟悉,请参见下面的代码:

Properties props = new Properties();
Field[] fields = config.getClass().getFields();
for (Field field : fields) {
    if (!field.getName().equals("oberservers")) {
        // is it a String[] field?
        if (field.getType().isArray()) {
            try {
                props.setProperty(field.getName(), String.join(";", /* how can I cast my String[] field here? */ );
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        else {
            try {
                props.setProperty(field.getName(), field.get(config).toString());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
   }
}
// ...
Writer writer = new OutputStreamWriter(new FileOutputStream(configFile), StandardCharsets.ISO_8859_1);
props.store(writer, "");
writer.close();
如何转换我的
字符串[]
字段?
这是一种干净的方法还是有一种更干净的方法


提前谢谢

听起来您真正想做的是序列化/反序列化
Config
对象。考虑使用其他更灵活的机制,而不是<代码>属性……当使用<代码>(String [])字段时会发生什么?GET(CONFIG)?无论如何,也许您应该看一看类似JSON的更简单的东西。在字符串数组的情况下,只需强制转换:
(string[])字段。get(config)
考虑使用首选项(带xml)而不是旧属性。看看这个问题:这个链接: