我正在尝试学习Java类的属性。我想打印出属性的关键字列表。但是,IDE显示以下错误:
Enumeration<Object> eo1 = p2.propertyNames();
//error, cast...propertyNames(...) to Enumeration我做了以下更改:
Enumeration<Object> eo1 = (Enumeration<Object>) p2.propertyNames();一切都很好。然而,我只是想知道为什么我需要将propertyNames()转换为Enumeration<Object>。我知道p2.propertyNames()返回一个枚举对象,但是它的语法对于像我这样的初学者来说是非常混乱的。
Properties p1 = new Properties();
try (OutputStream os1 = new FileOutputStream("random.txt")){
p1.setProperty("1", "one");
p1.setProperty("2", "two");
p1.setProperty("3", "three");
p1.store(os1, "comment");
} catch(IOException e){
e.printStackTrace();
}
Properties p2 = new Properties();
try (InputStream is1 = new FileInputStream("random.txt")){
p2.load(is1);
System.out.println(p2.getProperty("2"));
} catch (IOException e){
e.printStackTrace();
}
Enumeration<Object> eo1 = p2.propertyNames();
while (eo1.hasMoreElements()){
System.out.println(eo1.nextElement());
}发布于 2016-03-02 19:09:46
检查propertyNames()的返回类型。它不是枚举。它的public Enumeration<?> propertyNames()。两者都是不同的。阅读有关generics的更多信息
https://stackoverflow.com/questions/35745329
复制相似问题