从 java 属性文件加载 ArrayList<String>

loading ArrayList<String> from java properties file

我正在使用此方法读取属性文件:

public void loadConfigFromFile(String path) {
        Properties prop = new Properties();
        InputStream input = null;

        try {
            input = new FileInputStream(path);

            prop.load(input);

            /*saved like this:*/ //emails: abc@test.com, bbc@aab.com, ..
            String wordsS = prop.getProperty("keywords");
            String emailS = prop.getProperty("emails");
            String feedS = prop.getProperty("feeds");

            emails = Arrays.asList(emailS.split(",")); //ERROR !!
            words = Arrays.asList( wordsS.split(","))); //ERROR !!
            feeds = Arrays.asList( feedS.split(",")); //ERROR !!

        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

要写入的字段声明如下:

    private ArrayList<String> emails = new ArrayList<>(
            Arrays.asList("f00@b4r.com", "test@test.com")
    );

    private LinkedList<String> words = new LinkedList<>(
            Arrays.asList("vuln", "banana", "pizza", "bonanza")
    );

    private LinkedList<String> feeds = new LinkedList<>(
            Arrays.asList("http://www.kb.cert.org/vulfeed",
                    "https://ics-cert.us-cert.gov/advisories/advisories.xml")
    );

..所以编译器向我显示了以下信息,我不知道如何使用:

Incompatible types. Required ArrayList<String> but 'asList' was inferred to List<T>: no instance(s) of type variable(s) T exist so that List<T> conforms to ArrayList<String>

如何规避这个?

问题在于您分配给的已声明变量的类型 emails = Arrays.asList(emailS.split(","));.
根据编译错误,声明为ArrayList but Arrays.asList() returns a List.
您不能将 List 分配给 ArrayList,而您可以执行相反的操作。

除了 Arrays.asList() return 私有 class 的实例:java.util.Arrays.ArrayList 与您声明的 ArrayList 变量不同:java.util.ArrayList。因此,即使向下转换为 ArrayList 也不会起作用并导致 ClassCastException.

将声明的变量从 ArrayList<String> emailsList<String> emails 并对另外两个 ArrayList 变量做同样的事情。