使用接口和Map優(yōu)雅初始化枚舉

import java.util.HashMap;
import java.util.Map;

/**
 * @descrition 枚舉
 * @since 2020-05-21 18:00
 */
public class EnumInterface {
    String TYPE_FACE = "face";
    String TYPE_HUMAN_BODY = "humanBody";
    String TYPE_MOTOR_VEHICLE = "motorVehicle";
    String TYPE_NON_MOTOR_VEHICLE = "nonMotorVehicle";

    // 人臉特征
    String[] faceCharacteristics = new String[]
            {"Gender", "Hat", "Glass", "Mask"};

    // 人體特征
    String[] humanBodyCharacteristics = new String[]
            {"SleeveStyle", "UpperColor", "UpperTexture", "LowerType", "LowerColor", "ShoesStyle", "ShoesColor",
                    "HairStyle", "Bag", "Appendix", "AgeRange", "HumanBodyGender"};

    // 機動車特征
    String[] motorVehicleCharacteristics = new String[]
            {"PlateText", "VehicleClass", "VehicleColor", "VehicleHead", "PlateClass",
                    "PlateColor", "PlateState", "VehicleRoofItem", "VehicleFrontItem", "FaceCoveredItem", "SpecialVehicle"};

    // 非機動車特征
    String[] nonMotorVehicleCharacteristics = new String[]
            {"VehicleType", "VehicleColor", "VehicleHead", "IllegalPassenger", "Gender", "UpperStyle", "UpperColor", "Headwear", "PackStyle"};

    Map<String, String[]> search = new HashMap<String, String[]>() {
        {
            put(TYPE_FACE, faceCharacteristics);
            put(TYPE_HUMAN_BODY, humanBodyCharacteristics);
            put(TYPE_MOTOR_VEHICLE, motorVehicleCharacteristics);
            put(TYPE_NON_MOTOR_VEHICLE, nonMotorVehicleCharacteristics);
        }
    };

}

這里的雙括號”{{}}”用來初始化,使代碼簡潔易讀。
第一層括弧實際是定義了一個匿名內(nèi)部類 (Anonymous Inner Class),第二層括弧實際上是一個實例初始化塊 (instance initializer block),這個塊在內(nèi)部匿名類構(gòu)造時被執(zhí)行。
同理,list也可這樣賦值:

private List<String> list = new ArrayList<String>() {
        {
            add("tom");
            add("jerry");
            add("hkj");
        }
    };
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容