Как определить массив объектов в файле свойств и прочитать из программы Java - PullRequest
1 голос
/ 04 июня 2019

У меня есть такой файл свойств.

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

Как прочитать этот файл как список объектов класса {имя, значение} в простой Java-программе, используя ResourceBundle или Properties?

Вот класс.

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
  }
}

Ответы [ 2 ]

0 голосов
/ 04 июня 2019

Это решение, которое я написал, но оно включает 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
0 голосов
/ 04 июня 2019

Я не совсем понимаю, что вы хотите, поэтому не стесняйтесь поправлять меня и давать мне больше ограничений для работы, но вот простой способ прочитать файл 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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...