且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在java中按名称获取颜色

更新时间:2023-01-27 14:47:52

如果您的名字与Java的常量相对应,您可以使用反射来映射它们:

If your names correspond to those of Java's constants, you can use reflection to map them:

public static Color getColorByName(String name) {
    try {
        return (Color)Color.class.getField(name.toUpperCase()).get(null);
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
        return null;
    }
}