下面是一个示例,说明如何使用一点 Java 9 来做到这一点:
public static void main(String[] args) throws ParseException, ClassNotFoundException {
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter your color\n" +
"BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
List<Color> colorArray= new ArrayList<>();
Map<String, Color> colorMap = Map.ofEntries(entry("BLUE", Color.BLUE),
entry( "BLACK", Color.BLACK),
entry( "ORANGE", Color.ORANGE)); // TODO: add more colours
while(sc.hasNext()) {
String next = sc.next();
Color c = colorMap.get(next);
if(c == null) {
if("END".equals(next)) {
break;
}
System.err.printf("Sorry, could not find %s%n", next);
}
else {
colorArray.add(c);
System.out.printf("Added %s%n", c);
}
}
System.out.println(colorArray);
}
这是示例运行的输出:
Enter your color
BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:
> BLUE
Added java.awt.Color[r=0,g=0,b=255]
> BLACK
Added java.awt.Color[r=0,g=0,b=0]
> ORANGE
Added java.awt.Color[r=255,g=200,b=0]
> END
[java.awt.Color[r=0,g=0,b=255], java.awt.Color[r=0,g=0,b=0], java.awt.Color[r=255,g=200,b=0]]
这是基于@VHS 想法使用反射的另一个版本:
public static void main(String[] args) throws ParseException, ClassNotFoundException, IllegalAccessException {
Scanner sc = new Scanner(System.in);
System.out.println("\nEnter your color\n" +
"BLUE, BLACK, ORANGE, WHITE, YELLOW, RED, GREEN, PINK:");
List<Color> colorArray= new ArrayList<>();
Class<Color> colorClass = Color.class;
while(sc.hasNext()) {
String next = sc.next();
try {
Color c = colorClass.cast(colorClass.getField(next.toLowerCase()).get(null));
colorArray.add(c);
System.out.printf("Added %s%n", c);
} catch (NoSuchFieldException e) {
if("END".equals(next)) {
break;
}
System.err.printf("Sorry, could not find %s%n", next);
}
}
System.out.println(colorArray);
}
理想情况下,您应该结合这两种想法(使用贴图和反射),以便支持 java.awt.Color 中声明的颜色 + 未声明的颜色。