簡體   English   中英

如何在屬性文件中定義對象數組並從 Java 程序中讀取

[英]How to define array of objects in a properties file and read from Java program

我有一個這樣的屬性文件。

property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3

如何使用 ResourceBundle 或 Properties 在純 Java 程序中將此文件作為類 {name, value} 的對象列表讀取?

這是課堂。

public class XYZ {
  private String name;
  private String value;
  // Getters & Setters
}

我需要得到這樣的。

ArrayList<XYZ> propertiesList = SomeUtility.getProperties("property", XYZ.class);

實用程序類可能是這樣的。

public class SomeUtility {
  public static ArrayList getProperties(String key, Class cls) {
    //logic
  }
}

我可能不完全理解你想要什么所以隨時糾正我並給我更多的限制,但這里有一個簡單的方法來讀取位於項目中某處的Properties文件:

private static void readPropertiesFile(String path) throws IOException {

    java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
    Properties properties = new Properties();

    InputStream inputStream = new FileInputStream(path);
    properties.load(inputStream);

    for (String name : properties.stringPropertyNames()) {
        map.put(name, properties.getProperty(name));
    }
    for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
        System.out.printf("Property Key: %s, Property Value: %s%n", entry.getKey(), entry.getValue());
    }
}

輸出

Property Key: property[0].name, Property Value: A
Property Key: property[1].name, Property Value: B
Property Key: property[0].value, Property Value: 1
Property Key: property[1].value, Property Value: 2
Property Key: property[2].name, Property Value: C
Property Key: property[2].value, Property Value: 3

這是我寫的解決方案,但是涉及到Reflect和Gson。 有沒有更好的方法來做到這一點? 任何已經可用的像 Apache 一樣微調的東西。

import com.google.gson.Gson;
import com.google.gson.JsonObject;

import java.lang.reflect.Field;
import java.util.*;

public class ListResourceBundle {

    public static final Gson gson = new Gson();

    private final ResourceBundle bundle;

    public ListResourceBundle(ResourceBundle bundle) {
        this.bundle = bundle;
    }

    public List<?> getProperties(String key, Class<?> cls) {
        final int maxArraySize = getMaxArraySize(key, getMatchingKeys(key));
        final List<String> fields = getFields(cls);

        final List<Object> result = new ArrayList<>();
        for (int i = 0; i < maxArraySize; i++) {
            JsonObject jsonObject = new JsonObject();
            for (String field : fields) {
                jsonObject.addProperty(field, getStringOrNull(key + "[" + i + "]." + field));
            }

            result.add(gson.fromJson(jsonObject, cls));
        }

        System.out.println("result.toString() = " + result.toString());
        return result;
    }

    public List<String> getMatchingKeys(String key) {
        Enumeration<String> keys = bundle.getKeys();
        List<String> matchingKeys = new ArrayList<>();
        while(keys.hasMoreElements()) {
            String k = keys.nextElement();
            if(k.startsWith(key)) {
                matchingKeys.add(k);
            }
        }
        Collections.sort(matchingKeys);
        return matchingKeys;
    }

    public int getMaxArraySize(String key, List<String> matchingKeys) {
        int maxArraySize = 0;
        for (int i = 0; ; i++) {
            boolean indexAvailable = false;
            for (String matchingKey : matchingKeys) {
                if(matchingKey.startsWith(key + "[" + i + "]")) {
                    indexAvailable = true;
                    break;
                }
            }
            if(indexAvailable) {
                maxArraySize++;
            } else {
                break;
            }
        }

        return maxArraySize;
    }

    public String getStringOrNull(String key) {
        try {
            return bundle.getString(key);
        } catch (MissingResourceException e) {
            return null;
        }
    }

    public List<String> getFields(Class<?> cls) {
        final List<String> fields = new ArrayList<>();
        for (Field field : cls.getDeclaredFields()) {
            fields.add(field.getName());
        }
        return fields;
    }

    public static void main(String[] args) {
        ResourceBundle bundle = ResourceBundle.getBundle("com.example.application.resources.Resource");
        ListResourceBundle applicationResourceBundle = new ListResourceBundle(bundle);
        applicationResourceBundle.getProperties("property", ReportParam.class);
    }

}

資源:

property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3

輸出:

result.toString() = [
ReportParam{name='A', value='1'}, 
ReportParam{name='B', value='2'}, 
ReportParam{name='C', value='3'}]

Process finished with exit code 0

我知道答案有點晚了,但是如果我正確理解您的問題陳述,您可以使用:

@ConfigurationProperties

完成你的工作。 為了方便起見,這是我的帶有 YAML 文件的 spring-boot 示例(也可以通過屬性文件實現)。

應用程序.yaml:

xyz:
 xyzprops :
 -
  name: cbc
  value: 441
 - 
  name: obc
  value: 443

XYZ 類:

@Component
@ConfigurationProperties(prefix = "xyz")
public class XYZ{
    private List<XYZProps> xyzprops;

    public List<XYZProps> getXyzprops() {
        return xyzprops;
    }

    public void setXyzprops(List<XYZProps> xyzprops) {
        this.xyzprops = xyzprops;
    }
    
    public class XYZProps{
        String name;
        String value;
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getValue() {
            return value;
        }
        public void setValue(String value) {
            this.value = value;
        }
    }
}

然后@Autowire XYZ 你想在哪里使用它。

我會使用 JSON:

在您的文件中:
property=[{"name":"A","value":"1"},{"name":"B","value":"2"},{"name":"C","value":"3"}]

然后使用com.google.gson.gson (或任何其他)庫反序列化它:
ArrayList<XYZ> propertiesList;
propertiesList = new gsonbuilder().create().fromjson(property, propertiesList.class);

注意:我還沒有測試過這段代碼,而且我對 java 不是很熟悉,所以我確信有更好、更簡潔的方法來實現這一點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM