I'm trying to learn the Java class Properties. I want to print out the list of properties's key. However, the IDE displayed the following error:
Enumeration<Object> eo1 = p2.propertyNames();
//error, cast...propertyNames(...) to Enumeration
I made the following change:
Enumeration<Object> eo1 = (Enumeration<Object>) p2.propertyNames();
And everything works fine. However, I was just wondering why I need to cast propertyNames()
to Enumeration<Object>
. I know p2.propertyNames()
return a object of Enumeration, but the syntax is very confusing for a beginner like me.
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());
}
答案 0 :(得分:0)
检查propertyNames()的返回类型。它不是枚举。它的public Enumeration<?> propertyNames()
。两者都不同。详细了解generics