@SuppressWarnings("unchecked") private void mergeFromField(final Map.Entry<FieldDescriptorType, Object> entry) { final FieldDescriptorType descriptor = entry.getKey(); final Object otherValue = entry.getValue(); if (descriptor.isRepeated()) { Object value = fields.get(descriptor); if (value == null) { // Our list is empty, but we still need to make a defensive copy of // the other list since we don't know if the other FieldSet is still // mutable. fields.put(descriptor, new ArrayList((List) otherValue)); } else { // Concatenate the lists. ((List) value).addAll((List) otherValue); } } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { Object value = fields.get(descriptor); if (value == null) { fields.put(descriptor, otherValue); } else { // Merge the messages. fields.put( descriptor, descriptor .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) .build()); } } else { fields.put(descriptor, otherValue); } }
/** * Useful for implementing {@link * Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings("unchecked") public void addRepeatedField(final FieldDescriptorType descriptor, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "addRepeatedField() can only be called on repeated fields."); } verifyType(descriptor.getLiteType(), value); final Object existingValue = fields.get(descriptor); List list; if (existingValue == null) { list = new ArrayList(); fields.put(descriptor, list); } else { list = (List) existingValue; } list.add(value); }
/** * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings("unchecked") public void setField(final FieldDescriptorType descriptor, Object value) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } // Wrap the contents in a new list so that the caller cannot change // the list's contents after setting it. final List newList = new ArrayList(); newList.addAll((List) value); for (final Object element : newList) { verifyType(descriptor.getLiteType(), element); } value = newList; } else { verifyType(descriptor.getLiteType(), value); } fields.put(descriptor, value); }