Convert between java Object and String, Boolean, List, Date, Number types

 Application scenario: Create a class. This class has a Map<String, Object> attribute, but the Object type can only specify String, Boolean, List, Date, Number

code show as below:

  public static class Builder {
        private Map<String, Object> propertyMap = new HashMap<String, Object>();
       
        private Builder() {
        }

        public EventRecord build(){
         
            return new EventRecord(propertyMap);
        }


        public EventRecord.Builder addProperty(String key, String property) {
            addPropertyObject(key, property);
            return this;
        }

        public EventRecord.Builder addProperty(String key, boolean property) {
            addPropertyObject(key, property);
            return this;
        }

        public EventRecord.Builder addProperty(String key, Number property) {
            addPropertyObject(key, property);
            return this;
        }

        public EventRecord.Builder addProperty(String key, Date property) {
            addPropertyObject(key, property);
            return this;
        }

        public EventRecord.Builder addProperty(String key, List<String> property) {
            addPropertyObject(key, property);
            return this;
        }

        private void addPropertyObject(String key, Object property) {
            if (key != null) {
                propertyMap.put(key, property);
            }
        }
    }

This class does not allow external creation and can only build objects, parameters are not allowed to be set, only call addProperty() to initialize the corresponding type 

//        Object value = "asdhgashga";
//        Object value = new Date();
//        Object value = true;
//        Object value = 1241235132461l;
        Object value = new ArrayList<String>(){
   
   {
            add("1");
            add("4");
            add("5");
        }};
        if(value instanceof String){
            System.out.println((String)value);
        }else if(value instanceof Boolean){
            System.out.println((Boolean)value);
        }else if(value instanceof Number){
            System.out.println((Number)value);
        }else if(value instanceof Date){
            System.out.println((Date)value);
        }else if(value instanceof ArrayList<?>){
            List<String> result = new ArrayList<>();
            for (Object o : (List<?>) value) {
                result.add(String.class.cast(o));
            }
            System.out.println(result);
        }

Guess you like

Origin blog.csdn.net/gao_yuwushengchu/article/details/126244544