• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Protocol Buffers - Google's data interchange format
2 // Copyright 2008 Google Inc.  All rights reserved.
3 // https://developers.google.com/protocol-buffers/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 //     * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 //     * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 //     * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30 
31 package com.google.protobuf;
32 
33 import com.google.protobuf.Descriptors.Descriptor;
34 import com.google.protobuf.Descriptors.EnumDescriptor;
35 import com.google.protobuf.Descriptors.EnumValueDescriptor;
36 import com.google.protobuf.Descriptors.FieldDescriptor;
37 import com.google.protobuf.Descriptors.FileDescriptor;
38 import com.google.protobuf.Descriptors.OneofDescriptor;
39 
40 import java.io.IOException;
41 import java.io.InputStream;
42 import java.io.ObjectStreamException;
43 import java.io.Serializable;
44 import java.lang.reflect.InvocationTargetException;
45 import java.lang.reflect.Method;
46 import java.util.ArrayList;
47 import java.util.Collections;
48 import java.util.Iterator;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.TreeMap;
52 
53 /**
54  * All generated protocol message classes extend this class.  This class
55  * implements most of the Message and Builder interfaces using Java reflection.
56  * Users can ignore this class and pretend that generated messages implement
57  * the Message interface directly.
58  *
59  * @author kenton@google.com Kenton Varda
60  */
61 public abstract class GeneratedMessage extends AbstractMessage
62     implements Serializable {
63   private static final long serialVersionUID = 1L;
64 
65   /**
66    * For testing. Allows a test to disable the optimization that avoids using
67    * field builders for nested messages until they are requested. By disabling
68    * this optimization, existing tests can be reused to test the field builders.
69    */
70   protected static boolean alwaysUseFieldBuilders = false;
71 
72   /** For use by generated code only.  */
73   protected UnknownFieldSet unknownFields;
74 
GeneratedMessage()75   protected GeneratedMessage() {
76     unknownFields = UnknownFieldSet.getDefaultInstance();
77   }
78 
GeneratedMessage(Builder<?> builder)79   protected GeneratedMessage(Builder<?> builder) {
80     unknownFields = builder.getUnknownFields();
81   }
82 
83   @Override
getParserForType()84   public Parser<? extends GeneratedMessage> getParserForType() {
85     throw new UnsupportedOperationException(
86         "This is supposed to be overridden by subclasses.");
87   }
88 
89  /**
90   * For testing. Allows a test to disable the optimization that avoids using
91   * field builders for nested messages until they are requested. By disabling
92   * this optimization, existing tests can be reused to test the field builders.
93   * See {@link RepeatedFieldBuilder} and {@link SingleFieldBuilder}.
94   */
enableAlwaysUseFieldBuildersForTesting()95   static void enableAlwaysUseFieldBuildersForTesting() {
96     alwaysUseFieldBuilders = true;
97   }
98 
99   /**
100    * Get the FieldAccessorTable for this type.  We can't have the message
101    * class pass this in to the constructor because of bootstrapping trouble
102    * with DescriptorProtos.
103    */
internalGetFieldAccessorTable()104   protected abstract FieldAccessorTable internalGetFieldAccessorTable();
105 
106   @Override
getDescriptorForType()107   public Descriptor getDescriptorForType() {
108     return internalGetFieldAccessorTable().descriptor;
109   }
110 
111   /**
112    * Internal helper to return a modifiable map containing all the fields.
113    * The returned Map is modifialbe so that the caller can add additional
114    * extension fields to implement {@link #getAllFields()}.
115    *
116    * @param getBytesForString whether to generate ByteString for string fields
117    */
getAllFieldsMutable( boolean getBytesForString)118   private Map<FieldDescriptor, Object> getAllFieldsMutable(
119       boolean getBytesForString) {
120     final TreeMap<FieldDescriptor, Object> result =
121       new TreeMap<FieldDescriptor, Object>();
122     final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
123     final List<FieldDescriptor> fields = descriptor.getFields();
124 
125     for (int i = 0; i < fields.size(); i++) {
126       FieldDescriptor field = fields.get(i);
127       final OneofDescriptor oneofDescriptor = field.getContainingOneof();
128 
129       /*
130        * If the field is part of a Oneof, then at maximum one field in the Oneof is set
131        * and it is not repeated. There is no need to iterate through the others.
132        */
133       if (oneofDescriptor != null) {
134         // Skip other fields in the Oneof we know are not set
135         i += oneofDescriptor.getFieldCount() - 1;
136         if (!hasOneof(oneofDescriptor)) {
137           // If no field is set in the Oneof, skip all the fields in the Oneof
138           continue;
139         }
140         // Get the pointer to the only field which is set in the Oneof
141         field = getOneofFieldDescriptor(oneofDescriptor);
142       } else {
143         // If we are not in a Oneof, we need to check if the field is set and if it is repeated
144         if (field.isRepeated()) {
145           final List<?> value = (List<?>) getField(field);
146           if (!value.isEmpty()) {
147             result.put(field, value);
148           }
149           continue;
150         }
151         if (!hasField(field)) {
152           continue;
153         }
154       }
155       // Add the field to the map
156       if (getBytesForString && field.getJavaType() == FieldDescriptor.JavaType.STRING) {
157         result.put(field, getFieldRaw(field));
158       } else {
159         result.put(field, getField(field));
160       }
161     }
162     return result;
163   }
164 
165   @Override
isInitialized()166   public boolean isInitialized() {
167     for (final FieldDescriptor field : getDescriptorForType().getFields()) {
168       // Check that all required fields are present.
169       if (field.isRequired()) {
170         if (!hasField(field)) {
171           return false;
172         }
173       }
174       // Check that embedded messages are initialized.
175       if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
176         if (field.isRepeated()) {
177           @SuppressWarnings("unchecked") final
178           List<Message> messageList = (List<Message>) getField(field);
179           for (final Message element : messageList) {
180             if (!element.isInitialized()) {
181               return false;
182             }
183           }
184         } else {
185           if (hasField(field) && !((Message) getField(field)).isInitialized()) {
186             return false;
187           }
188         }
189       }
190     }
191 
192     return true;
193   }
194 
195   @Override
getAllFields()196   public Map<FieldDescriptor, Object> getAllFields() {
197     return Collections.unmodifiableMap(
198         getAllFieldsMutable(/* getBytesForString = */ false));
199   }
200 
201   /**
202    * Returns a collection of all the fields in this message which are set
203    * and their corresponding values.  A singular ("required" or "optional")
204    * field is set iff hasField() returns true for that field.  A "repeated"
205    * field is set iff getRepeatedFieldCount() is greater than zero.  The
206    * values are exactly what would be returned by calling
207    * {@link #getFieldRaw(Descriptors.FieldDescriptor)} for each field.  The map
208    * is guaranteed to be a sorted map, so iterating over it will return fields
209    * in order by field number.
210    */
getAllFieldsRaw()211   Map<FieldDescriptor, Object> getAllFieldsRaw() {
212     return Collections.unmodifiableMap(
213         getAllFieldsMutable(/* getBytesForString = */ true));
214   }
215 
216   @Override
hasOneof(final OneofDescriptor oneof)217   public boolean hasOneof(final OneofDescriptor oneof) {
218     return internalGetFieldAccessorTable().getOneof(oneof).has(this);
219   }
220 
221   @Override
getOneofFieldDescriptor(final OneofDescriptor oneof)222   public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) {
223     return internalGetFieldAccessorTable().getOneof(oneof).get(this);
224   }
225 
226   @Override
hasField(final FieldDescriptor field)227   public boolean hasField(final FieldDescriptor field) {
228     return internalGetFieldAccessorTable().getField(field).has(this);
229   }
230 
231   @Override
getField(final FieldDescriptor field)232   public Object getField(final FieldDescriptor field) {
233     return internalGetFieldAccessorTable().getField(field).get(this);
234   }
235 
236   /**
237    * Obtains the value of the given field, or the default value if it is
238    * not set.  For primitive fields, the boxed primitive value is returned.
239    * For enum fields, the EnumValueDescriptor for the value is returned. For
240    * embedded message fields, the sub-message is returned.  For repeated
241    * fields, a java.util.List is returned. For present string fields, a
242    * ByteString is returned representing the bytes that the field contains.
243    */
getFieldRaw(final FieldDescriptor field)244   Object getFieldRaw(final FieldDescriptor field) {
245     return internalGetFieldAccessorTable().getField(field).getRaw(this);
246   }
247 
248   @Override
getRepeatedFieldCount(final FieldDescriptor field)249   public int getRepeatedFieldCount(final FieldDescriptor field) {
250     return internalGetFieldAccessorTable().getField(field)
251       .getRepeatedCount(this);
252   }
253 
254   @Override
getRepeatedField(final FieldDescriptor field, final int index)255   public Object getRepeatedField(final FieldDescriptor field, final int index) {
256     return internalGetFieldAccessorTable().getField(field)
257       .getRepeated(this, index);
258   }
259 
260   @Override
getUnknownFields()261   public UnknownFieldSet getUnknownFields() {
262     throw new UnsupportedOperationException(
263         "This is supposed to be overridden by subclasses.");
264   }
265 
266   /**
267    * Called by subclasses to parse an unknown field.
268    * @return {@code true} unless the tag is an end-group tag.
269    */
parseUnknownField( CodedInputStream input, UnknownFieldSet.Builder unknownFields, ExtensionRegistryLite extensionRegistry, int tag)270   protected boolean parseUnknownField(
271       CodedInputStream input,
272       UnknownFieldSet.Builder unknownFields,
273       ExtensionRegistryLite extensionRegistry,
274       int tag) throws IOException {
275     return unknownFields.mergeFieldFrom(tag, input);
276   }
277 
parseWithIOException(Parser<M> parser, InputStream input)278   protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input)
279       throws IOException {
280     try {
281       return parser.parseFrom(input);
282     } catch (InvalidProtocolBufferException e) {
283       throw e.unwrapIOException();
284     }
285   }
286 
parseWithIOException(Parser<M> parser, InputStream input, ExtensionRegistryLite extensions)287   protected static <M extends Message> M parseWithIOException(Parser<M> parser, InputStream input,
288       ExtensionRegistryLite extensions) throws IOException {
289     try {
290       return parser.parseFrom(input, extensions);
291     } catch (InvalidProtocolBufferException e) {
292       throw e.unwrapIOException();
293     }
294   }
295 
parseWithIOException(Parser<M> parser, CodedInputStream input)296   protected static <M extends Message> M parseWithIOException(Parser<M> parser,
297       CodedInputStream input) throws IOException {
298     try {
299       return parser.parseFrom(input);
300     } catch (InvalidProtocolBufferException e) {
301       throw e.unwrapIOException();
302     }
303   }
304 
parseWithIOException(Parser<M> parser, CodedInputStream input, ExtensionRegistryLite extensions)305   protected static <M extends Message> M parseWithIOException(Parser<M> parser,
306       CodedInputStream input, ExtensionRegistryLite extensions) throws IOException {
307     try {
308       return parser.parseFrom(input, extensions);
309     } catch (InvalidProtocolBufferException e) {
310       throw e.unwrapIOException();
311     }
312   }
313 
parseDelimitedWithIOException(Parser<M> parser, InputStream input)314   protected static <M extends Message> M parseDelimitedWithIOException(Parser<M> parser,
315       InputStream input) throws IOException {
316     try {
317       return parser.parseDelimitedFrom(input);
318     } catch (InvalidProtocolBufferException e) {
319       throw e.unwrapIOException();
320     }
321   }
322 
parseDelimitedWithIOException(Parser<M> parser, InputStream input, ExtensionRegistryLite extensions)323   protected static <M extends Message> M parseDelimitedWithIOException(Parser<M> parser,
324       InputStream input, ExtensionRegistryLite extensions) throws IOException {
325     try {
326       return parser.parseDelimitedFrom(input, extensions);
327     } catch (InvalidProtocolBufferException e) {
328       throw e.unwrapIOException();
329     }
330   }
331 
332   @Override
writeTo(final CodedOutputStream output)333   public void writeTo(final CodedOutputStream output) throws IOException {
334     MessageReflection.writeMessageTo(this, getAllFieldsRaw(), output, false);
335   }
336 
337   @Override
getSerializedSize()338   public int getSerializedSize() {
339     int size = memoizedSize;
340     if (size != -1) {
341       return size;
342     }
343 
344     memoizedSize = MessageReflection.getSerializedSize(
345         this, getAllFieldsRaw());
346     return memoizedSize;
347   }
348 
349 
350 
351   /**
352    * Used by parsing constructors in generated classes.
353    */
makeExtensionsImmutable()354   protected void makeExtensionsImmutable() {
355     // Noop for messages without extensions.
356   }
357 
358   /**
359    * TODO(xiaofeng): remove this after b/29368482 is fixed. We need to move this
360    * interface to AbstractMessage in order to versioning GeneratedMessage but
361    * this move breaks binary compatibility for AppEngine. After AppEngine is
362    * fixed we can exclude this from google3.
363    */
364   protected interface BuilderParent extends AbstractMessage.BuilderParent {}
365 
366   /**
367    * TODO(xiaofeng): remove this together with GeneratedMessage.BuilderParent.
368    */
newBuilderForType(BuilderParent parent)369   protected abstract Message.Builder newBuilderForType(BuilderParent parent);
370 
371   @Override
newBuilderForType(final AbstractMessage.BuilderParent parent)372   protected Message.Builder newBuilderForType(final AbstractMessage.BuilderParent parent) {
373     return newBuilderForType(new BuilderParent() {
374       @Override
375       public void markDirty() {
376         parent.markDirty();
377       }
378     });
379   }
380 
381 
382   @SuppressWarnings("unchecked")
383   public abstract static class Builder <BuilderType extends Builder<BuilderType>>
384       extends AbstractMessage.Builder<BuilderType> {
385 
386     private BuilderParent builderParent;
387 
388     private BuilderParentImpl meAsParent;
389 
390     // Indicates that we've built a message and so we are now obligated
391     // to dispatch dirty invalidations. See GeneratedMessage.BuilderListener.
392     private boolean isClean;
393 
394     private UnknownFieldSet unknownFields =
395         UnknownFieldSet.getDefaultInstance();
396 
397     protected Builder() {
398       this(null);
399     }
400 
401     protected Builder(BuilderParent builderParent) {
402       this.builderParent = builderParent;
403     }
404 
405     @Override
406     void dispose() {
407       builderParent = null;
408     }
409 
410     /**
411      * Called by the subclass when a message is built.
412      */
413     protected void onBuilt() {
414       if (builderParent != null) {
415         markClean();
416       }
417     }
418 
419     /**
420      * Called by the subclass or a builder to notify us that a message was
421      * built and may be cached and therefore invalidations are needed.
422      */
423     @Override
424     protected void markClean() {
425       this.isClean = true;
426     }
427 
428     /**
429      * Gets whether invalidations are needed
430      *
431      * @return whether invalidations are needed
432      */
433     protected boolean isClean() {
434       return isClean;
435     }
436 
437     @Override
438     public BuilderType clone() {
439       BuilderType builder =
440           (BuilderType) getDefaultInstanceForType().newBuilderForType();
441       builder.mergeFrom(buildPartial());
442       return builder;
443     }
444 
445     /**
446      * Called by the initialization and clear code paths to allow subclasses to
447      * reset any of their builtin fields back to the initial values.
448      */
449     @Override
450     public BuilderType clear() {
451       unknownFields = UnknownFieldSet.getDefaultInstance();
452       onChanged();
453       return (BuilderType) this;
454     }
455 
456     /**
457      * Get the FieldAccessorTable for this type.  We can't have the message
458      * class pass this in to the constructor because of bootstrapping trouble
459      * with DescriptorProtos.
460      */
461     protected abstract FieldAccessorTable internalGetFieldAccessorTable();
462 
463     @Override
464     public Descriptor getDescriptorForType() {
465       return internalGetFieldAccessorTable().descriptor;
466     }
467 
468     @Override
469     public Map<FieldDescriptor, Object> getAllFields() {
470       return Collections.unmodifiableMap(getAllFieldsMutable());
471     }
472 
473     /** Internal helper which returns a mutable map. */
474     private Map<FieldDescriptor, Object> getAllFieldsMutable() {
475       final TreeMap<FieldDescriptor, Object> result =
476         new TreeMap<FieldDescriptor, Object>();
477       final Descriptor descriptor = internalGetFieldAccessorTable().descriptor;
478       final List<FieldDescriptor> fields = descriptor.getFields();
479 
480       for (int i = 0; i < fields.size(); i++) {
481         FieldDescriptor field = fields.get(i);
482         final OneofDescriptor oneofDescriptor = field.getContainingOneof();
483 
484         /*
485          * If the field is part of a Oneof, then at maximum one field in the Oneof is set
486          * and it is not repeated. There is no need to iterate through the others.
487          */
488         if (oneofDescriptor != null) {
489           // Skip other fields in the Oneof we know are not set
490           i += oneofDescriptor.getFieldCount() - 1;
491           if (!hasOneof(oneofDescriptor)) {
492             // If no field is set in the Oneof, skip all the fields in the Oneof
493             continue;
494           }
495           // Get the pointer to the only field which is set in the Oneof
496           field = getOneofFieldDescriptor(oneofDescriptor);
497         } else {
498           // If we are not in a Oneof, we need to check if the field is set and if it is repeated
499           if (field.isRepeated()) {
500             final List<?> value = (List<?>) getField(field);
501             if (!value.isEmpty()) {
502               result.put(field, value);
503             }
504             continue;
505           }
506           if (!hasField(field)) {
507             continue;
508           }
509         }
510         // Add the field to the map
511         result.put(field, getField(field));
512       }
513       return result;
514     }
515 
516     @Override
517     public Message.Builder newBuilderForField(final FieldDescriptor field) {
518       return internalGetFieldAccessorTable().getField(field).newBuilder();
519     }
520 
521     @Override
522     public Message.Builder getFieldBuilder(final FieldDescriptor field) {
523       return internalGetFieldAccessorTable().getField(field).getBuilder(this);
524     }
525 
526     @Override
527     public Message.Builder getRepeatedFieldBuilder(final FieldDescriptor field, int index) {
528       return internalGetFieldAccessorTable().getField(field).getRepeatedBuilder(
529           this, index);
530     }
531 
532     @Override
533     public boolean hasOneof(final OneofDescriptor oneof) {
534       return internalGetFieldAccessorTable().getOneof(oneof).has(this);
535     }
536 
537     @Override
538     public FieldDescriptor getOneofFieldDescriptor(final OneofDescriptor oneof) {
539       return internalGetFieldAccessorTable().getOneof(oneof).get(this);
540     }
541 
542     @Override
543     public boolean hasField(final FieldDescriptor field) {
544       return internalGetFieldAccessorTable().getField(field).has(this);
545     }
546 
547     @Override
548     public Object getField(final FieldDescriptor field) {
549       Object object = internalGetFieldAccessorTable().getField(field).get(this);
550       if (field.isRepeated()) {
551         // The underlying list object is still modifiable at this point.
552         // Make sure not to expose the modifiable list to the caller.
553         return Collections.unmodifiableList((List) object);
554       } else {
555         return object;
556       }
557     }
558 
559     @Override
560     public BuilderType setField(final FieldDescriptor field, final Object value) {
561       internalGetFieldAccessorTable().getField(field).set(this, value);
562       return (BuilderType) this;
563     }
564 
565     @Override
566     public BuilderType clearField(final FieldDescriptor field) {
567       internalGetFieldAccessorTable().getField(field).clear(this);
568       return (BuilderType) this;
569     }
570 
571     @Override
572     public BuilderType clearOneof(final OneofDescriptor oneof) {
573       internalGetFieldAccessorTable().getOneof(oneof).clear(this);
574       return (BuilderType) this;
575     }
576 
577     @Override
578     public int getRepeatedFieldCount(final FieldDescriptor field) {
579       return internalGetFieldAccessorTable().getField(field)
580           .getRepeatedCount(this);
581     }
582 
583     @Override
584     public Object getRepeatedField(final FieldDescriptor field, final int index) {
585       return internalGetFieldAccessorTable().getField(field)
586           .getRepeated(this, index);
587     }
588 
589     @Override
590     public BuilderType setRepeatedField(
591         final FieldDescriptor field, final int index, final Object value) {
592       internalGetFieldAccessorTable().getField(field)
593         .setRepeated(this, index, value);
594       return (BuilderType) this;
595     }
596 
597     @Override
598     public BuilderType addRepeatedField(final FieldDescriptor field, final Object value) {
599       internalGetFieldAccessorTable().getField(field).addRepeated(this, value);
600       return (BuilderType) this;
601     }
602 
603     @Override
604     public BuilderType setUnknownFields(final UnknownFieldSet unknownFields) {
605       this.unknownFields = unknownFields;
606       onChanged();
607       return (BuilderType) this;
608     }
609 
610     @Override
611     public BuilderType mergeUnknownFields(
612         final UnknownFieldSet unknownFields) {
613       this.unknownFields =
614         UnknownFieldSet.newBuilder(this.unknownFields)
615                        .mergeFrom(unknownFields)
616                        .build();
617       onChanged();
618       return (BuilderType) this;
619     }
620 
621     @Override
622     public boolean isInitialized() {
623       for (final FieldDescriptor field : getDescriptorForType().getFields()) {
624         // Check that all required fields are present.
625         if (field.isRequired()) {
626           if (!hasField(field)) {
627             return false;
628           }
629         }
630         // Check that embedded messages are initialized.
631         if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
632           if (field.isRepeated()) {
633             @SuppressWarnings("unchecked") final
634             List<Message> messageList = (List<Message>) getField(field);
635             for (final Message element : messageList) {
636               if (!element.isInitialized()) {
637                 return false;
638               }
639             }
640           } else {
641             if (hasField(field) &&
642                 !((Message) getField(field)).isInitialized()) {
643               return false;
644             }
645           }
646         }
647       }
648       return true;
649     }
650 
651     @Override
652     public final UnknownFieldSet getUnknownFields() {
653       return unknownFields;
654     }
655 
656     /**
657      * Called by subclasses to parse an unknown field.
658      * @return {@code true} unless the tag is an end-group tag.
659      */
660     protected boolean parseUnknownField(
661         final CodedInputStream input,
662         final UnknownFieldSet.Builder unknownFields,
663         final ExtensionRegistryLite extensionRegistry,
664         final int tag) throws IOException {
665       return unknownFields.mergeFieldFrom(tag, input);
666     }
667 
668     /**
669      * Implementation of {@link BuilderParent} for giving to our children. This
670      * small inner class makes it so we don't publicly expose the BuilderParent
671      * methods.
672      */
673     private class BuilderParentImpl implements BuilderParent {
674 
675       @Override
676       public void markDirty() {
677         onChanged();
678       }
679     }
680 
681     /**
682      * Gets the {@link BuilderParent} for giving to our children.
683      * @return The builder parent for our children.
684      */
685     protected BuilderParent getParentForChildren() {
686       if (meAsParent == null) {
687         meAsParent = new BuilderParentImpl();
688       }
689       return meAsParent;
690     }
691 
692     /**
693      * Called when a the builder or one of its nested children has changed
694      * and any parent should be notified of its invalidation.
695      */
696     protected final void onChanged() {
697       if (isClean && builderParent != null) {
698         builderParent.markDirty();
699 
700         // Don't keep dispatching invalidations until build is called again.
701         isClean = false;
702       }
703     }
704 
705     /**
706      * Gets the map field with the given field number. This method should be
707      * overridden in the generated message class if the message contains map
708      * fields.
709      *
710      * Unlike other field types, reflection support for map fields can't be
711      * implemented based on generated public API because we need to access a
712      * map field as a list in reflection API but the generated API only allows
713      * us to access it as a map. This method returns the underlying map field
714      * directly and thus enables us to access the map field as a list.
715      */
716     @SuppressWarnings({"unused", "rawtypes"})
717     protected MapField internalGetMapField(int fieldNumber) {
718       // Note that we can't use descriptor names here because this method will
719       // be called when descriptor is being initialized.
720       throw new RuntimeException(
721           "No map fields found in " + getClass().getName());
722     }
723 
724     /** Like {@link #internalGetMapField} but return a mutable version. */
725     @SuppressWarnings({"unused", "rawtypes"})
726     protected MapField internalGetMutableMapField(int fieldNumber) {
727       // Note that we can't use descriptor names here because this method will
728       // be called when descriptor is being initialized.
729       throw new RuntimeException(
730           "No map fields found in " + getClass().getName());
731     }
732   }
733 
734   // =================================================================
735   // Extensions-related stuff
736 
737   public interface ExtendableMessageOrBuilder<
738       MessageType extends ExtendableMessage> extends MessageOrBuilder {
739     // Re-define for return type covariance.
740     @Override
741     Message getDefaultInstanceForType();
742 
743     /** Check if a singular extension is present. */
744     <Type> boolean hasExtension(
745         ExtensionLite<MessageType, Type> extension);
746 
747     /** Get the number of elements in a repeated extension. */
748     <Type> int getExtensionCount(
749         ExtensionLite<MessageType, List<Type>> extension);
750 
751     /** Get the value of an extension. */
752     <Type> Type getExtension(
753         ExtensionLite<MessageType, Type> extension);
754 
755     /** Get one element of a repeated extension. */
756     <Type> Type getExtension(
757         ExtensionLite<MessageType, List<Type>> extension,
758         int index);
759 
760     /** Check if a singular extension is present. */
761     <Type> boolean hasExtension(
762         Extension<MessageType, Type> extension);
763     /** Check if a singular extension is present. */
764     <Type> boolean hasExtension(
765         GeneratedExtension<MessageType, Type> extension);
766     /** Get the number of elements in a repeated extension. */
767     <Type> int getExtensionCount(
768         Extension<MessageType, List<Type>> extension);
769     /** Get the number of elements in a repeated extension. */
770     <Type> int getExtensionCount(
771         GeneratedExtension<MessageType, List<Type>> extension);
772     /** Get the value of an extension. */
773     <Type> Type getExtension(
774         Extension<MessageType, Type> extension);
775     /** Get the value of an extension. */
776     <Type> Type getExtension(
777         GeneratedExtension<MessageType, Type> extension);
778     /** Get one element of a repeated extension. */
779     <Type> Type getExtension(
780         Extension<MessageType, List<Type>> extension,
781         int index);
782     /** Get one element of a repeated extension. */
783     <Type> Type getExtension(
784         GeneratedExtension<MessageType, List<Type>> extension,
785         int index);
786   }
787 
788   /**
789    * Generated message classes for message types that contain extension ranges
790    * subclass this.
791    *
792    * <p>This class implements type-safe accessors for extensions.  They
793    * implement all the same operations that you can do with normal fields --
794    * e.g. "has", "get", and "getCount" -- but for extensions.  The extensions
795    * are identified using instances of the class {@link GeneratedExtension};
796    * the protocol compiler generates a static instance of this class for every
797    * extension in its input.  Through the magic of generics, all is made
798    * type-safe.
799    *
800    * <p>For example, imagine you have the {@code .proto} file:
801    *
802    * <pre>
803    * option java_class = "MyProto";
804    *
805    * message Foo {
806    *   extensions 1000 to max;
807    * }
808    *
809    * extend Foo {
810    *   optional int32 bar;
811    * }
812    * </pre>
813    *
814    * <p>Then you might write code like:
815    *
816    * <pre>
817    * MyProto.Foo foo = getFoo();
818    * int i = foo.getExtension(MyProto.bar);
819    * </pre>
820    *
821    * <p>See also {@link ExtendableBuilder}.
822    */
823   public abstract static class ExtendableMessage<
824         MessageType extends ExtendableMessage>
825       extends GeneratedMessage
826       implements ExtendableMessageOrBuilder<MessageType> {
827 
828     private static final long serialVersionUID = 1L;
829 
830     private final FieldSet<FieldDescriptor> extensions;
831 
832     protected ExtendableMessage() {
833       this.extensions = FieldSet.newFieldSet();
834     }
835 
836     protected ExtendableMessage(
837         ExtendableBuilder<MessageType, ?> builder) {
838       super(builder);
839       this.extensions = builder.buildExtensions();
840     }
841 
842     private void verifyExtensionContainingType(
843         final Extension<MessageType, ?> extension) {
844       if (extension.getDescriptor().getContainingType() !=
845           getDescriptorForType()) {
846         // This can only happen if someone uses unchecked operations.
847         throw new IllegalArgumentException(
848           "Extension is for type \"" +
849           extension.getDescriptor().getContainingType().getFullName() +
850           "\" which does not match message type \"" +
851           getDescriptorForType().getFullName() + "\".");
852       }
853     }
854 
855     /** Check if a singular extension is present. */
856     @Override
857     @SuppressWarnings("unchecked")
858     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extensionLite) {
859       Extension<MessageType, Type> extension = checkNotLite(extensionLite);
860 
861       verifyExtensionContainingType(extension);
862       return extensions.hasField(extension.getDescriptor());
863     }
864 
865     /** Get the number of elements in a repeated extension. */
866     @Override
867     @SuppressWarnings("unchecked")
868     public final <Type> int getExtensionCount(
869         final ExtensionLite<MessageType, List<Type>> extensionLite) {
870       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
871 
872       verifyExtensionContainingType(extension);
873       final FieldDescriptor descriptor = extension.getDescriptor();
874       return extensions.getRepeatedFieldCount(descriptor);
875     }
876 
877     /** Get the value of an extension. */
878     @Override
879     @SuppressWarnings("unchecked")
880     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extensionLite) {
881       Extension<MessageType, Type> extension = checkNotLite(extensionLite);
882 
883       verifyExtensionContainingType(extension);
884       FieldDescriptor descriptor = extension.getDescriptor();
885       final Object value = extensions.getField(descriptor);
886       if (value == null) {
887         if (descriptor.isRepeated()) {
888           return (Type) Collections.emptyList();
889         } else if (descriptor.getJavaType() ==
890                    FieldDescriptor.JavaType.MESSAGE) {
891           return (Type) extension.getMessageDefaultInstance();
892         } else {
893           return (Type) extension.fromReflectionType(
894               descriptor.getDefaultValue());
895         }
896       } else {
897         return (Type) extension.fromReflectionType(value);
898       }
899     }
900 
901     /** Get one element of a repeated extension. */
902     @Override
903     @SuppressWarnings("unchecked")
904     public final <Type> Type getExtension(
905         final ExtensionLite<MessageType, List<Type>> extensionLite, final int index) {
906       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
907 
908       verifyExtensionContainingType(extension);
909       FieldDescriptor descriptor = extension.getDescriptor();
910       return (Type) extension.singularFromReflectionType(
911           extensions.getRepeatedField(descriptor, index));
912     }
913 
914     /** Check if a singular extension is present. */
915     @Override
916     public final <Type> boolean hasExtension(final Extension<MessageType, Type> extension) {
917       return hasExtension((ExtensionLite<MessageType, Type>) extension);
918     }
919     /** Check if a singular extension is present. */
920     @Override
921     public final <Type> boolean hasExtension(
922         final GeneratedExtension<MessageType, Type> extension) {
923       return hasExtension((ExtensionLite<MessageType, Type>) extension);
924     }
925     /** Get the number of elements in a repeated extension. */
926     @Override
927     public final <Type> int getExtensionCount(
928         final Extension<MessageType, List<Type>> extension) {
929       return getExtensionCount((ExtensionLite<MessageType, List<Type>>) extension);
930     }
931     /** Get the number of elements in a repeated extension. */
932     @Override
933     public final <Type> int getExtensionCount(
934         final GeneratedExtension<MessageType, List<Type>> extension) {
935       return getExtensionCount((ExtensionLite<MessageType, List<Type>>) extension);
936     }
937     /** Get the value of an extension. */
938     @Override
939     public final <Type> Type getExtension(final Extension<MessageType, Type> extension) {
940       return getExtension((ExtensionLite<MessageType, Type>) extension);
941     }
942     /** Get the value of an extension. */
943     @Override
944     public final <Type> Type getExtension(
945         final GeneratedExtension<MessageType, Type> extension) {
946       return getExtension((ExtensionLite<MessageType, Type>) extension);
947     }
948     /** Get one element of a repeated extension. */
949     @Override
950     public final <Type> Type getExtension(
951         final Extension<MessageType, List<Type>> extension, final int index) {
952       return getExtension((ExtensionLite<MessageType, List<Type>>) extension, index);
953     }
954     /** Get one element of a repeated extension. */
955     @Override
956     public final <Type> Type getExtension(
957         final GeneratedExtension<MessageType, List<Type>> extension, final int index) {
958       return getExtension((ExtensionLite<MessageType, List<Type>>) extension, index);
959     }
960 
961     /** Called by subclasses to check if all extensions are initialized. */
962     protected boolean extensionsAreInitialized() {
963       return extensions.isInitialized();
964     }
965 
966     @Override
967     public boolean isInitialized() {
968       return super.isInitialized() && extensionsAreInitialized();
969     }
970 
971     @Override
972     protected boolean parseUnknownField(
973         CodedInputStream input,
974         UnknownFieldSet.Builder unknownFields,
975         ExtensionRegistryLite extensionRegistry,
976         int tag) throws IOException {
977       return MessageReflection.mergeFieldFrom(
978           input, unknownFields, extensionRegistry, getDescriptorForType(),
979           new MessageReflection.ExtensionAdapter(extensions), tag);
980     }
981 
982 
983     /**
984      * Used by parsing constructors in generated classes.
985      */
986     @Override
987     protected void makeExtensionsImmutable() {
988       extensions.makeImmutable();
989     }
990 
991     /**
992      * Used by subclasses to serialize extensions.  Extension ranges may be
993      * interleaved with field numbers, but we must write them in canonical
994      * (sorted by field number) order.  ExtensionWriter helps us write
995      * individual ranges of extensions at once.
996      */
997     protected class ExtensionWriter {
998       // Imagine how much simpler this code would be if Java iterators had
999       // a way to get the next element without advancing the iterator.
1000 
1001       private final Iterator<Map.Entry<FieldDescriptor, Object>> iter =
1002         extensions.iterator();
1003       private Map.Entry<FieldDescriptor, Object> next;
1004       private final boolean messageSetWireFormat;
1005 
1006       private ExtensionWriter(final boolean messageSetWireFormat) {
1007         if (iter.hasNext()) {
1008           next = iter.next();
1009         }
1010         this.messageSetWireFormat = messageSetWireFormat;
1011       }
1012 
1013       public void writeUntil(final int end, final CodedOutputStream output)
1014                              throws IOException {
1015         while (next != null && next.getKey().getNumber() < end) {
1016           FieldDescriptor descriptor = next.getKey();
1017           if (messageSetWireFormat && descriptor.getLiteJavaType() ==
1018                   WireFormat.JavaType.MESSAGE &&
1019               !descriptor.isRepeated()) {
1020             if (next instanceof LazyField.LazyEntry<?>) {
1021               output.writeRawMessageSetExtension(descriptor.getNumber(),
1022                   ((LazyField.LazyEntry<?>) next).getField().toByteString());
1023             } else {
1024               output.writeMessageSetExtension(descriptor.getNumber(),
1025                                               (Message) next.getValue());
1026             }
1027           } else {
1028             // TODO(xiangl): Taken care of following code, it may cause
1029             // problem when we use LazyField for normal fields/extensions.
1030             // Due to the optional field can be duplicated at the end of
1031             // serialized bytes, which will make the serialized size change
1032             // after lazy field parsed. So when we use LazyField globally,
1033             // we need to change the following write method to write cached
1034             // bytes directly rather than write the parsed message.
1035             FieldSet.writeField(descriptor, next.getValue(), output);
1036           }
1037           if (iter.hasNext()) {
1038             next = iter.next();
1039           } else {
1040             next = null;
1041           }
1042         }
1043       }
1044     }
1045 
1046     protected ExtensionWriter newExtensionWriter() {
1047       return new ExtensionWriter(false);
1048     }
1049     protected ExtensionWriter newMessageSetExtensionWriter() {
1050       return new ExtensionWriter(true);
1051     }
1052 
1053     /** Called by subclasses to compute the size of extensions. */
1054     protected int extensionsSerializedSize() {
1055       return extensions.getSerializedSize();
1056     }
1057     protected int extensionsSerializedSizeAsMessageSet() {
1058       return extensions.getMessageSetSerializedSize();
1059     }
1060 
1061     // ---------------------------------------------------------------
1062     // Reflection
1063 
1064     protected Map<FieldDescriptor, Object> getExtensionFields() {
1065       return extensions.getAllFields();
1066     }
1067 
1068     @Override
1069     public Map<FieldDescriptor, Object> getAllFields() {
1070       final Map<FieldDescriptor, Object> result =
1071           super.getAllFieldsMutable(/* getBytesForString = */ false);
1072       result.putAll(getExtensionFields());
1073       return Collections.unmodifiableMap(result);
1074     }
1075 
1076     @Override
1077     public Map<FieldDescriptor, Object> getAllFieldsRaw() {
1078       final Map<FieldDescriptor, Object> result =
1079           super.getAllFieldsMutable(/* getBytesForString = */ false);
1080       result.putAll(getExtensionFields());
1081       return Collections.unmodifiableMap(result);
1082     }
1083 
1084     @Override
1085     public boolean hasField(final FieldDescriptor field) {
1086       if (field.isExtension()) {
1087         verifyContainingType(field);
1088         return extensions.hasField(field);
1089       } else {
1090         return super.hasField(field);
1091       }
1092     }
1093 
1094     @Override
1095     public Object getField(final FieldDescriptor field) {
1096       if (field.isExtension()) {
1097         verifyContainingType(field);
1098         final Object value = extensions.getField(field);
1099         if (value == null) {
1100           if (field.isRepeated()) {
1101             return Collections.emptyList();
1102           } else if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
1103             // Lacking an ExtensionRegistry, we have no way to determine the
1104             // extension's real type, so we return a DynamicMessage.
1105             return DynamicMessage.getDefaultInstance(field.getMessageType());
1106           } else {
1107             return field.getDefaultValue();
1108           }
1109         } else {
1110           return value;
1111         }
1112       } else {
1113         return super.getField(field);
1114       }
1115     }
1116 
1117     @Override
1118     public int getRepeatedFieldCount(final FieldDescriptor field) {
1119       if (field.isExtension()) {
1120         verifyContainingType(field);
1121         return extensions.getRepeatedFieldCount(field);
1122       } else {
1123         return super.getRepeatedFieldCount(field);
1124       }
1125     }
1126 
1127     @Override
1128     public Object getRepeatedField(final FieldDescriptor field,
1129                                    final int index) {
1130       if (field.isExtension()) {
1131         verifyContainingType(field);
1132         return extensions.getRepeatedField(field, index);
1133       } else {
1134         return super.getRepeatedField(field, index);
1135       }
1136     }
1137 
1138     private void verifyContainingType(final FieldDescriptor field) {
1139       if (field.getContainingType() != getDescriptorForType()) {
1140         throw new IllegalArgumentException(
1141           "FieldDescriptor does not match message type.");
1142       }
1143     }
1144   }
1145 
1146   /**
1147    * Generated message builders for message types that contain extension ranges
1148    * subclass this.
1149    *
1150    * <p>This class implements type-safe accessors for extensions.  They
1151    * implement all the same operations that you can do with normal fields --
1152    * e.g. "get", "set", and "add" -- but for extensions.  The extensions are
1153    * identified using instances of the class {@link GeneratedExtension}; the
1154    * protocol compiler generates a static instance of this class for every
1155    * extension in its input.  Through the magic of generics, all is made
1156    * type-safe.
1157    *
1158    * <p>For example, imagine you have the {@code .proto} file:
1159    *
1160    * <pre>
1161    * option java_class = "MyProto";
1162    *
1163    * message Foo {
1164    *   extensions 1000 to max;
1165    * }
1166    *
1167    * extend Foo {
1168    *   optional int32 bar;
1169    * }
1170    * </pre>
1171    *
1172    * <p>Then you might write code like:
1173    *
1174    * <pre>
1175    * MyProto.Foo foo =
1176    *   MyProto.Foo.newBuilder()
1177    *     .setExtension(MyProto.bar, 123)
1178    *     .build();
1179    * </pre>
1180    *
1181    * <p>See also {@link ExtendableMessage}.
1182    */
1183   @SuppressWarnings("unchecked")
1184   public abstract static class ExtendableBuilder<
1185         MessageType extends ExtendableMessage,
1186         BuilderType extends ExtendableBuilder<MessageType, BuilderType>>
1187       extends Builder<BuilderType>
1188       implements ExtendableMessageOrBuilder<MessageType> {
1189 
1190     private FieldSet<FieldDescriptor> extensions = FieldSet.emptySet();
1191 
1192     protected ExtendableBuilder() {}
1193 
1194     protected ExtendableBuilder(
1195         BuilderParent parent) {
1196       super(parent);
1197     }
1198 
1199     // For immutable message conversion.
1200     void internalSetExtensionSet(FieldSet<FieldDescriptor> extensions) {
1201       this.extensions = extensions;
1202     }
1203 
1204     @Override
1205     public BuilderType clear() {
1206       extensions = FieldSet.emptySet();
1207       return super.clear();
1208     }
1209 
1210     // This is implemented here only to work around an apparent bug in the
1211     // Java compiler and/or build system.  See bug #1898463.  The mere presence
1212     // of this clone() implementation makes it go away.
1213     @Override
1214     public BuilderType clone() {
1215       return super.clone();
1216     }
1217 
1218     private void ensureExtensionsIsMutable() {
1219       if (extensions.isImmutable()) {
1220         extensions = extensions.clone();
1221       }
1222     }
1223 
1224     private void verifyExtensionContainingType(
1225         final Extension<MessageType, ?> extension) {
1226       if (extension.getDescriptor().getContainingType() !=
1227           getDescriptorForType()) {
1228         // This can only happen if someone uses unchecked operations.
1229         throw new IllegalArgumentException(
1230           "Extension is for type \"" +
1231           extension.getDescriptor().getContainingType().getFullName() +
1232           "\" which does not match message type \"" +
1233           getDescriptorForType().getFullName() + "\".");
1234       }
1235     }
1236 
1237     /** Check if a singular extension is present. */
1238     @Override
1239     public final <Type> boolean hasExtension(final ExtensionLite<MessageType, Type> extensionLite) {
1240       Extension<MessageType, Type> extension = checkNotLite(extensionLite);
1241 
1242       verifyExtensionContainingType(extension);
1243       return extensions.hasField(extension.getDescriptor());
1244     }
1245 
1246     /** Get the number of elements in a repeated extension. */
1247     @Override
1248     public final <Type> int getExtensionCount(
1249         final ExtensionLite<MessageType, List<Type>> extensionLite) {
1250       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
1251 
1252       verifyExtensionContainingType(extension);
1253       final FieldDescriptor descriptor = extension.getDescriptor();
1254       return extensions.getRepeatedFieldCount(descriptor);
1255     }
1256 
1257     /** Get the value of an extension. */
1258     @Override
1259     public final <Type> Type getExtension(final ExtensionLite<MessageType, Type> extensionLite) {
1260       Extension<MessageType, Type> extension = checkNotLite(extensionLite);
1261 
1262       verifyExtensionContainingType(extension);
1263       FieldDescriptor descriptor = extension.getDescriptor();
1264       final Object value = extensions.getField(descriptor);
1265       if (value == null) {
1266         if (descriptor.isRepeated()) {
1267           return (Type) Collections.emptyList();
1268         } else if (descriptor.getJavaType() ==
1269                    FieldDescriptor.JavaType.MESSAGE) {
1270           return (Type) extension.getMessageDefaultInstance();
1271         } else {
1272           return (Type) extension.fromReflectionType(
1273               descriptor.getDefaultValue());
1274         }
1275       } else {
1276         return (Type) extension.fromReflectionType(value);
1277       }
1278     }
1279 
1280     /** Get one element of a repeated extension. */
1281     @Override
1282     public final <Type> Type getExtension(
1283         final ExtensionLite<MessageType, List<Type>> extensionLite, final int index) {
1284       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
1285 
1286       verifyExtensionContainingType(extension);
1287       FieldDescriptor descriptor = extension.getDescriptor();
1288       return (Type) extension.singularFromReflectionType(
1289           extensions.getRepeatedField(descriptor, index));
1290     }
1291 
1292     /** Set the value of an extension. */
1293     public final <Type> BuilderType setExtension(
1294         final ExtensionLite<MessageType, Type> extensionLite,
1295         final Type value) {
1296       Extension<MessageType, Type> extension = checkNotLite(extensionLite);
1297 
1298       verifyExtensionContainingType(extension);
1299       ensureExtensionsIsMutable();
1300       final FieldDescriptor descriptor = extension.getDescriptor();
1301       extensions.setField(descriptor, extension.toReflectionType(value));
1302       onChanged();
1303       return (BuilderType) this;
1304     }
1305 
1306     /** Set the value of one element of a repeated extension. */
1307     public final <Type> BuilderType setExtension(
1308         final ExtensionLite<MessageType, List<Type>> extensionLite,
1309         final int index, final Type value) {
1310       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
1311 
1312       verifyExtensionContainingType(extension);
1313       ensureExtensionsIsMutable();
1314       final FieldDescriptor descriptor = extension.getDescriptor();
1315       extensions.setRepeatedField(
1316         descriptor, index,
1317         extension.singularToReflectionType(value));
1318       onChanged();
1319       return (BuilderType) this;
1320     }
1321 
1322     /** Append a value to a repeated extension. */
1323     public final <Type> BuilderType addExtension(
1324         final ExtensionLite<MessageType, List<Type>> extensionLite,
1325         final Type value) {
1326       Extension<MessageType, List<Type>> extension = checkNotLite(extensionLite);
1327 
1328       verifyExtensionContainingType(extension);
1329       ensureExtensionsIsMutable();
1330       final FieldDescriptor descriptor = extension.getDescriptor();
1331       extensions.addRepeatedField(
1332           descriptor, extension.singularToReflectionType(value));
1333       onChanged();
1334       return (BuilderType) this;
1335     }
1336 
1337     /** Clear an extension. */
1338     public final <Type> BuilderType clearExtension(
1339         final ExtensionLite<MessageType, ?> extensionLite) {
1340       Extension<MessageType, ?> extension = checkNotLite(extensionLite);
1341 
1342       verifyExtensionContainingType(extension);
1343       ensureExtensionsIsMutable();
1344       extensions.clearField(extension.getDescriptor());
1345       onChanged();
1346       return (BuilderType) this;
1347     }
1348 
1349     /** Check if a singular extension is present. */
1350     @Override
1351     public final <Type> boolean hasExtension(final Extension<MessageType, Type> extension) {
1352       return hasExtension((ExtensionLite<MessageType, Type>) extension);
1353     }
1354     /** Check if a singular extension is present. */
1355     @Override
1356     public final <Type> boolean hasExtension(
1357         final GeneratedExtension<MessageType, Type> extension) {
1358       return hasExtension((ExtensionLite<MessageType, Type>) extension);
1359     }
1360     /** Get the number of elements in a repeated extension. */
1361     @Override
1362     public final <Type> int getExtensionCount(
1363         final Extension<MessageType, List<Type>> extension) {
1364       return getExtensionCount((ExtensionLite<MessageType, List<Type>>) extension);
1365     }
1366     /** Get the number of elements in a repeated extension. */
1367     @Override
1368     public final <Type> int getExtensionCount(
1369         final GeneratedExtension<MessageType, List<Type>> extension) {
1370       return getExtensionCount((ExtensionLite<MessageType, List<Type>>) extension);
1371     }
1372     /** Get the value of an extension. */
1373     @Override
1374     public final <Type> Type getExtension(final Extension<MessageType, Type> extension) {
1375       return getExtension((ExtensionLite<MessageType, Type>) extension);
1376     }
1377     /** Get the value of an extension. */
1378     @Override
1379     public final <Type> Type getExtension(
1380         final GeneratedExtension<MessageType, Type> extension) {
1381       return getExtension((ExtensionLite<MessageType, Type>) extension);
1382     }
1383     /** Get the value of an extension. */
1384     @Override
1385     public final <Type> Type getExtension(
1386         final Extension<MessageType, List<Type>> extension, final int index) {
1387       return getExtension((ExtensionLite<MessageType, List<Type>>) extension, index);
1388     }
1389     /** Get the value of an extension. */
1390     @Override
1391     public final <Type> Type getExtension(
1392         final GeneratedExtension<MessageType, List<Type>> extension, final int index) {
1393       return getExtension((ExtensionLite<MessageType, List<Type>>) extension, index);
1394     }
1395     /** Set the value of an extension. */
1396     public final <Type> BuilderType setExtension(
1397         final Extension<MessageType, Type> extension, final Type value) {
1398       return setExtension((ExtensionLite<MessageType, Type>) extension, value);
1399     }
1400     /** Set the value of an extension. */
1401     public <Type> BuilderType setExtension(
1402         final GeneratedExtension<MessageType, Type> extension, final Type value) {
1403       return setExtension((ExtensionLite<MessageType, Type>) extension, value);
1404     }
1405     /** Set the value of one element of a repeated extension. */
1406     public final <Type> BuilderType setExtension(
1407         final Extension<MessageType, List<Type>> extension,
1408         final int index, final Type value) {
1409       return setExtension((ExtensionLite<MessageType, List<Type>>) extension, index, value);
1410     }
1411     /** Set the value of one element of a repeated extension. */
1412     public <Type> BuilderType setExtension(
1413         final GeneratedExtension<MessageType, List<Type>> extension,
1414         final int index, final Type value) {
1415       return setExtension((ExtensionLite<MessageType, List<Type>>) extension, index, value);
1416     }
1417     /** Append a value to a repeated extension. */
1418     public final <Type> BuilderType addExtension(
1419         final Extension<MessageType, List<Type>> extension, final Type value) {
1420       return addExtension((ExtensionLite<MessageType, List<Type>>) extension, value);
1421     }
1422     /** Append a value to a repeated extension. */
1423     public <Type> BuilderType addExtension(
1424         final GeneratedExtension<MessageType, List<Type>> extension, final Type value) {
1425       return addExtension((ExtensionLite<MessageType, List<Type>>) extension, value);
1426     }
1427     /** Clear an extension. */
1428     public final <Type> BuilderType clearExtension(
1429         final Extension<MessageType, ?> extension) {
1430       return clearExtension((ExtensionLite<MessageType, ?>) extension);
1431     }
1432     /** Clear an extension. */
1433     public <Type> BuilderType clearExtension(
1434         final GeneratedExtension<MessageType, ?> extension) {
1435       return clearExtension((ExtensionLite<MessageType, ?>) extension);
1436     }
1437 
1438     /** Called by subclasses to check if all extensions are initialized. */
1439     protected boolean extensionsAreInitialized() {
1440       return extensions.isInitialized();
1441     }
1442 
1443     /**
1444      * Called by the build code path to create a copy of the extensions for
1445      * building the message.
1446      */
1447     private FieldSet<FieldDescriptor> buildExtensions() {
1448       extensions.makeImmutable();
1449       return extensions;
1450     }
1451 
1452     @Override
1453     public boolean isInitialized() {
1454       return super.isInitialized() && extensionsAreInitialized();
1455     }
1456 
1457     /**
1458      * Called by subclasses to parse an unknown field or an extension.
1459      * @return {@code true} unless the tag is an end-group tag.
1460      */
1461     @Override
1462     protected boolean parseUnknownField(
1463         final CodedInputStream input,
1464         final UnknownFieldSet.Builder unknownFields,
1465         final ExtensionRegistryLite extensionRegistry,
1466         final int tag) throws IOException {
1467       return MessageReflection.mergeFieldFrom(
1468           input, unknownFields, extensionRegistry, getDescriptorForType(),
1469           new MessageReflection.BuilderAdapter(this), tag);
1470     }
1471 
1472     // ---------------------------------------------------------------
1473     // Reflection
1474 
1475     @Override
1476     public Map<FieldDescriptor, Object> getAllFields() {
1477       final Map<FieldDescriptor, Object> result = super.getAllFieldsMutable();
1478       result.putAll(extensions.getAllFields());
1479       return Collections.unmodifiableMap(result);
1480     }
1481 
1482     @Override
1483     public Object getField(final FieldDescriptor field) {
1484       if (field.isExtension()) {
1485         verifyContainingType(field);
1486         final Object value = extensions.getField(field);
1487         if (value == null) {
1488           if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
1489             // Lacking an ExtensionRegistry, we have no way to determine the
1490             // extension's real type, so we return a DynamicMessage.
1491             return DynamicMessage.getDefaultInstance(field.getMessageType());
1492           } else {
1493             return field.getDefaultValue();
1494           }
1495         } else {
1496           return value;
1497         }
1498       } else {
1499         return super.getField(field);
1500       }
1501     }
1502 
1503     @Override
1504     public int getRepeatedFieldCount(final FieldDescriptor field) {
1505       if (field.isExtension()) {
1506         verifyContainingType(field);
1507         return extensions.getRepeatedFieldCount(field);
1508       } else {
1509         return super.getRepeatedFieldCount(field);
1510       }
1511     }
1512 
1513     @Override
1514     public Object getRepeatedField(final FieldDescriptor field,
1515                                    final int index) {
1516       if (field.isExtension()) {
1517         verifyContainingType(field);
1518         return extensions.getRepeatedField(field, index);
1519       } else {
1520         return super.getRepeatedField(field, index);
1521       }
1522     }
1523 
1524     @Override
1525     public boolean hasField(final FieldDescriptor field) {
1526       if (field.isExtension()) {
1527         verifyContainingType(field);
1528         return extensions.hasField(field);
1529       } else {
1530         return super.hasField(field);
1531       }
1532     }
1533 
1534     @Override
1535     public BuilderType setField(final FieldDescriptor field,
1536                                 final Object value) {
1537       if (field.isExtension()) {
1538         verifyContainingType(field);
1539         ensureExtensionsIsMutable();
1540         extensions.setField(field, value);
1541         onChanged();
1542         return (BuilderType) this;
1543       } else {
1544         return super.setField(field, value);
1545       }
1546     }
1547 
1548     @Override
1549     public BuilderType clearField(final FieldDescriptor field) {
1550       if (field.isExtension()) {
1551         verifyContainingType(field);
1552         ensureExtensionsIsMutable();
1553         extensions.clearField(field);
1554         onChanged();
1555         return (BuilderType) this;
1556       } else {
1557         return super.clearField(field);
1558       }
1559     }
1560 
1561     @Override
1562     public BuilderType setRepeatedField(final FieldDescriptor field,
1563                                         final int index, final Object value) {
1564       if (field.isExtension()) {
1565         verifyContainingType(field);
1566         ensureExtensionsIsMutable();
1567         extensions.setRepeatedField(field, index, value);
1568         onChanged();
1569         return (BuilderType) this;
1570       } else {
1571         return super.setRepeatedField(field, index, value);
1572       }
1573     }
1574 
1575     @Override
1576     public BuilderType addRepeatedField(final FieldDescriptor field,
1577                                         final Object value) {
1578       if (field.isExtension()) {
1579         verifyContainingType(field);
1580         ensureExtensionsIsMutable();
1581         extensions.addRepeatedField(field, value);
1582         onChanged();
1583         return (BuilderType) this;
1584       } else {
1585         return super.addRepeatedField(field, value);
1586       }
1587     }
1588 
1589     protected final void mergeExtensionFields(final ExtendableMessage other) {
1590       ensureExtensionsIsMutable();
1591       extensions.mergeFrom(other.extensions);
1592       onChanged();
1593     }
1594 
1595     private void verifyContainingType(final FieldDescriptor field) {
1596       if (field.getContainingType() != getDescriptorForType()) {
1597         throw new IllegalArgumentException(
1598           "FieldDescriptor does not match message type.");
1599       }
1600     }
1601   }
1602 
1603   // -----------------------------------------------------------------
1604 
1605   /**
1606    * Gets the descriptor for an extension. The implementation depends on whether
1607    * the extension is scoped in the top level of a file or scoped in a Message.
1608    */
1609   static interface ExtensionDescriptorRetriever {
1610     FieldDescriptor getDescriptor();
1611   }
1612 
1613   /** For use by generated code only. */
1614   public static <ContainingType extends Message, Type>
1615       GeneratedExtension<ContainingType, Type>
1616       newMessageScopedGeneratedExtension(final Message scope,
1617                                          final int descriptorIndex,
1618                                          final Class singularType,
1619                                          final Message defaultInstance) {
1620     // For extensions scoped within a Message, we use the Message to resolve
1621     // the outer class's descriptor, from which the extension descriptor is
1622     // obtained.
1623     return new GeneratedExtension<ContainingType, Type>(
1624         new CachedDescriptorRetriever() {
1625           @Override
1626           public FieldDescriptor loadDescriptor() {
1627             return scope.getDescriptorForType().getExtensions().get(descriptorIndex);
1628           }
1629         },
1630         singularType,
1631         defaultInstance,
1632         Extension.ExtensionType.IMMUTABLE);
1633   }
1634 
1635   /** For use by generated code only. */
1636   public static <ContainingType extends Message, Type>
1637      GeneratedExtension<ContainingType, Type>
1638      newFileScopedGeneratedExtension(final Class singularType,
1639                                      final Message defaultInstance) {
1640     // For extensions scoped within a file, we rely on the outer class's
1641     // static initializer to call internalInit() on the extension when the
1642     // descriptor is available.
1643     return new GeneratedExtension<ContainingType, Type>(
1644         null,  // ExtensionDescriptorRetriever is initialized in internalInit();
1645         singularType,
1646         defaultInstance,
1647         Extension.ExtensionType.IMMUTABLE);
1648   }
1649 
1650   private abstract static class CachedDescriptorRetriever
1651       implements ExtensionDescriptorRetriever {
1652     private volatile FieldDescriptor descriptor;
1653     protected abstract FieldDescriptor loadDescriptor();
1654 
1655     @Override
1656     public FieldDescriptor getDescriptor() {
1657       if (descriptor == null) {
1658         synchronized (this) {
1659           if (descriptor == null) {
1660             descriptor = loadDescriptor();
1661           }
1662         }
1663       }
1664       return descriptor;
1665     }
1666   }
1667 
1668   /**
1669    * Used in proto1 generated code only.
1670    *
1671    * After enabling bridge, we can define proto2 extensions (the extended type
1672    * is a proto2 mutable message) in a proto1 .proto file. For these extensions
1673    * we should generate proto2 GeneratedExtensions.
1674    */
1675   public static <ContainingType extends Message, Type>
1676       GeneratedExtension<ContainingType, Type>
1677       newMessageScopedGeneratedExtension(
1678           final Message scope, final String name,
1679           final Class singularType, final Message defaultInstance) {
1680     // For extensions scoped within a Message, we use the Message to resolve
1681     // the outer class's descriptor, from which the extension descriptor is
1682     // obtained.
1683     return new GeneratedExtension<ContainingType, Type>(
1684         new CachedDescriptorRetriever() {
1685           @Override
1686           protected FieldDescriptor loadDescriptor() {
1687             return scope.getDescriptorForType().findFieldByName(name);
1688           }
1689         },
1690         singularType,
1691         defaultInstance,
1692         Extension.ExtensionType.MUTABLE);
1693   }
1694 
1695   /**
1696    * Used in proto1 generated code only.
1697    *
1698    * After enabling bridge, we can define proto2 extensions (the extended type
1699    * is a proto2 mutable message) in a proto1 .proto file. For these extensions
1700    * we should generate proto2 GeneratedExtensions.
1701    */
1702   public static <ContainingType extends Message, Type>
1703      GeneratedExtension<ContainingType, Type>
1704      newFileScopedGeneratedExtension(
1705          final Class singularType, final Message defaultInstance,
1706          final String descriptorOuterClass, final String extensionName) {
1707     // For extensions scoped within a file, we load the descriptor outer
1708     // class and rely on it to get the FileDescriptor which then can be
1709     // used to obtain the extension's FieldDescriptor.
1710     return new GeneratedExtension<ContainingType, Type>(
1711         new CachedDescriptorRetriever() {
1712           @Override
1713           protected FieldDescriptor loadDescriptor() {
1714             try {
1715               Class clazz = singularType.getClassLoader().loadClass(descriptorOuterClass);
1716               FileDescriptor file = (FileDescriptor) clazz.getField("descriptor").get(null);
1717               return file.findExtensionByName(extensionName);
1718             } catch (Exception e) {
1719               throw new RuntimeException(
1720                   "Cannot load descriptors: "
1721                       + descriptorOuterClass
1722                       + " is not a valid descriptor class name",
1723                   e);
1724             }
1725           }
1726         },
1727         singularType,
1728         defaultInstance,
1729         Extension.ExtensionType.MUTABLE);
1730   }
1731 
1732   /**
1733    * Type used to represent generated extensions.  The protocol compiler
1734    * generates a static singleton instance of this class for each extension.
1735    *
1736    * <p>For example, imagine you have the {@code .proto} file:
1737    *
1738    * <pre>
1739    * option java_class = "MyProto";
1740    *
1741    * message Foo {
1742    *   extensions 1000 to max;
1743    * }
1744    *
1745    * extend Foo {
1746    *   optional int32 bar;
1747    * }
1748    * </pre>
1749    *
1750    * <p>Then, {@code MyProto.Foo.bar} has type
1751    * {@code GeneratedExtension<MyProto.Foo, Integer>}.
1752    *
1753    * <p>In general, users should ignore the details of this type, and simply use
1754    * these static singletons as parameters to the extension accessors defined
1755    * in {@link ExtendableMessage} and {@link ExtendableBuilder}.
1756    */
1757   public static class GeneratedExtension<
1758       ContainingType extends Message, Type> extends
1759       Extension<ContainingType, Type> {
1760     // TODO(kenton):  Find ways to avoid using Java reflection within this
1761     //   class.  Also try to avoid suppressing unchecked warnings.
1762 
1763     // We can't always initialize the descriptor of a GeneratedExtension when
1764     // we first construct it due to initialization order difficulties (namely,
1765     // the descriptor may not have been constructed yet, since it is often
1766     // constructed by the initializer of a separate module).
1767     //
1768     // In the case of nested extensions, we initialize the
1769     // ExtensionDescriptorRetriever with an instance that uses the scoping
1770     // Message's default instance to retrieve the extension's descriptor.
1771     //
1772     // In the case of non-nested extensions, we initialize the
1773     // ExtensionDescriptorRetriever to null and rely on the outer class's static
1774     // initializer to call internalInit() after the descriptor has been parsed.
1775     GeneratedExtension(ExtensionDescriptorRetriever descriptorRetriever,
1776         Class singularType,
1777         Message messageDefaultInstance,
1778         ExtensionType extensionType) {
1779       if (Message.class.isAssignableFrom(singularType) &&
1780           !singularType.isInstance(messageDefaultInstance)) {
1781         throw new IllegalArgumentException(
1782             "Bad messageDefaultInstance for " + singularType.getName());
1783       }
1784       this.descriptorRetriever = descriptorRetriever;
1785       this.singularType = singularType;
1786       this.messageDefaultInstance = messageDefaultInstance;
1787 
1788       if (ProtocolMessageEnum.class.isAssignableFrom(singularType)) {
1789         this.enumValueOf = getMethodOrDie(singularType, "valueOf",
1790                                           EnumValueDescriptor.class);
1791         this.enumGetValueDescriptor =
1792             getMethodOrDie(singularType, "getValueDescriptor");
1793       } else {
1794         this.enumValueOf = null;
1795         this.enumGetValueDescriptor = null;
1796       }
1797       this.extensionType = extensionType;
1798     }
1799 
1800     /** For use by generated code only. */
1801     public void internalInit(final FieldDescriptor descriptor) {
1802       if (descriptorRetriever != null) {
1803         throw new IllegalStateException("Already initialized.");
1804       }
1805       descriptorRetriever =
1806           new ExtensionDescriptorRetriever() {
1807             @Override
1808             public FieldDescriptor getDescriptor() {
1809               return descriptor;
1810             }
1811           };
1812     }
1813 
1814     private ExtensionDescriptorRetriever descriptorRetriever;
1815     private final Class singularType;
1816     private final Message messageDefaultInstance;
1817     private final Method enumValueOf;
1818     private final Method enumGetValueDescriptor;
1819     private final ExtensionType extensionType;
1820 
1821     @Override
1822     public FieldDescriptor getDescriptor() {
1823       if (descriptorRetriever == null) {
1824         throw new IllegalStateException(
1825             "getDescriptor() called before internalInit()");
1826       }
1827       return descriptorRetriever.getDescriptor();
1828     }
1829 
1830     /**
1831      * If the extension is an embedded message or group, returns the default
1832      * instance of the message.
1833      */
1834     @Override
1835     public Message getMessageDefaultInstance() {
1836       return messageDefaultInstance;
1837     }
1838 
1839     @Override
1840     protected ExtensionType getExtensionType() {
1841       return extensionType;
1842     }
1843 
1844     /**
1845      * Convert from the type used by the reflection accessors to the type used
1846      * by native accessors.  E.g., for enums, the reflection accessors use
1847      * EnumValueDescriptors but the native accessors use the generated enum
1848      * type.
1849      */
1850     @Override
1851     @SuppressWarnings("unchecked")
1852     protected Object fromReflectionType(final Object value) {
1853       FieldDescriptor descriptor = getDescriptor();
1854       if (descriptor.isRepeated()) {
1855         if (descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE ||
1856             descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) {
1857           // Must convert the whole list.
1858           final List result = new ArrayList();
1859           for (final Object element : (List) value) {
1860             result.add(singularFromReflectionType(element));
1861           }
1862           return result;
1863         } else {
1864           return value;
1865         }
1866       } else {
1867         return singularFromReflectionType(value);
1868       }
1869     }
1870 
1871     /**
1872      * Like {@link #fromReflectionType(Object)}, but if the type is a repeated
1873      * type, this converts a single element.
1874      */
1875     @Override
1876     protected Object singularFromReflectionType(final Object value) {
1877       FieldDescriptor descriptor = getDescriptor();
1878       switch (descriptor.getJavaType()) {
1879         case MESSAGE:
1880           if (singularType.isInstance(value)) {
1881             return value;
1882           } else {
1883             return messageDefaultInstance.newBuilderForType()
1884                 .mergeFrom((Message) value).build();
1885           }
1886         case ENUM:
1887           return invokeOrDie(enumValueOf, null, (EnumValueDescriptor) value);
1888         default:
1889           return value;
1890       }
1891     }
1892 
1893     /**
1894      * Convert from the type used by the native accessors to the type used
1895      * by reflection accessors.  E.g., for enums, the reflection accessors use
1896      * EnumValueDescriptors but the native accessors use the generated enum
1897      * type.
1898      */
1899     @Override
1900     @SuppressWarnings("unchecked")
1901     protected Object toReflectionType(final Object value) {
1902       FieldDescriptor descriptor = getDescriptor();
1903       if (descriptor.isRepeated()) {
1904         if (descriptor.getJavaType() == FieldDescriptor.JavaType.ENUM) {
1905           // Must convert the whole list.
1906           final List result = new ArrayList();
1907           for (final Object element : (List) value) {
1908             result.add(singularToReflectionType(element));
1909           }
1910           return result;
1911         } else {
1912           return value;
1913         }
1914       } else {
1915         return singularToReflectionType(value);
1916       }
1917     }
1918 
1919     /**
1920      * Like {@link #toReflectionType(Object)}, but if the type is a repeated
1921      * type, this converts a single element.
1922      */
1923     @Override
1924     protected Object singularToReflectionType(final Object value) {
1925       FieldDescriptor descriptor = getDescriptor();
1926       switch (descriptor.getJavaType()) {
1927         case ENUM:
1928           return invokeOrDie(enumGetValueDescriptor, value);
1929         default:
1930           return value;
1931       }
1932     }
1933 
1934     @Override
1935     public int getNumber() {
1936       return getDescriptor().getNumber();
1937     }
1938 
1939     @Override
1940     public WireFormat.FieldType getLiteType() {
1941       return getDescriptor().getLiteType();
1942     }
1943 
1944     @Override
1945     public boolean isRepeated() {
1946       return getDescriptor().isRepeated();
1947     }
1948 
1949     @Override
1950     @SuppressWarnings("unchecked")
1951     public Type getDefaultValue() {
1952       if (isRepeated()) {
1953         return (Type) Collections.emptyList();
1954       }
1955       if (getDescriptor().getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
1956         return (Type) messageDefaultInstance;
1957       }
1958       return (Type) singularFromReflectionType(
1959           getDescriptor().getDefaultValue());
1960     }
1961   }
1962 
1963   // =================================================================
1964 
1965   /** Calls Class.getMethod and throws a RuntimeException if it fails. */
1966   @SuppressWarnings("unchecked")
1967   private static Method getMethodOrDie(
1968       final Class clazz, final String name, final Class... params) {
1969     try {
1970       return clazz.getMethod(name, params);
1971     } catch (NoSuchMethodException e) {
1972       throw new RuntimeException(
1973         "Generated message class \"" + clazz.getName() +
1974         "\" missing method \"" + name + "\".", e);
1975     }
1976   }
1977 
1978   /** Calls invoke and throws a RuntimeException if it fails. */
1979   private static Object invokeOrDie(
1980       final Method method, final Object object, final Object... params) {
1981     try {
1982       return method.invoke(object, params);
1983     } catch (IllegalAccessException e) {
1984       throw new RuntimeException(
1985         "Couldn't use Java reflection to implement protocol message " +
1986         "reflection.", e);
1987     } catch (InvocationTargetException e) {
1988       final Throwable cause = e.getCause();
1989       if (cause instanceof RuntimeException) {
1990         throw (RuntimeException) cause;
1991       } else if (cause instanceof Error) {
1992         throw (Error) cause;
1993       } else {
1994         throw new RuntimeException(
1995           "Unexpected exception thrown by generated accessor method.", cause);
1996       }
1997     }
1998   }
1999 
2000   /**
2001    * Gets the map field with the given field number. This method should be
2002    * overridden in the generated message class if the message contains map
2003    * fields.
2004    *
2005    * Unlike other field types, reflection support for map fields can't be
2006    * implemented based on generated public API because we need to access a
2007    * map field as a list in reflection API but the generated API only allows
2008    * us to access it as a map. This method returns the underlying map field
2009    * directly and thus enables us to access the map field as a list.
2010    */
2011   @SuppressWarnings({"rawtypes", "unused"})
2012   protected MapField internalGetMapField(int fieldNumber) {
2013     // Note that we can't use descriptor names here because this method will
2014     // be called when descriptor is being initialized.
2015     throw new RuntimeException(
2016         "No map fields found in " + getClass().getName());
2017   }
2018 
2019   /**
2020    * Users should ignore this class.  This class provides the implementation
2021    * with access to the fields of a message object using Java reflection.
2022    */
2023   public static final class FieldAccessorTable {
2024 
2025     /**
2026      * Construct a FieldAccessorTable for a particular message class.  Only
2027      * one FieldAccessorTable should ever be constructed per class.
2028      *
2029      * @param descriptor     The type's descriptor.
2030      * @param camelCaseNames The camelcase names of all fields in the message.
2031      *                       These are used to derive the accessor method names.
2032      * @param messageClass   The message type.
2033      * @param builderClass   The builder type.
2034      */
2035     public FieldAccessorTable(
2036         final Descriptor descriptor,
2037         final String[] camelCaseNames,
2038         final Class<? extends GeneratedMessage> messageClass,
2039         final Class<? extends Builder> builderClass) {
2040       this(descriptor, camelCaseNames);
2041       ensureFieldAccessorsInitialized(messageClass, builderClass);
2042     }
2043 
2044     /**
2045      * Construct a FieldAccessorTable for a particular message class without
2046      * initializing FieldAccessors.
2047      */
2048     public FieldAccessorTable(
2049         final Descriptor descriptor,
2050         final String[] camelCaseNames) {
2051       this.descriptor = descriptor;
2052       this.camelCaseNames = camelCaseNames;
2053       fields = new FieldAccessor[descriptor.getFields().size()];
2054       oneofs = new OneofAccessor[descriptor.getOneofs().size()];
2055       initialized = false;
2056     }
2057 
2058     private boolean isMapFieldEnabled(FieldDescriptor field) {
2059       boolean result = true;
2060       return result;
2061     }
2062 
2063     /**
2064      * Ensures the field accessors are initialized. This method is thread-safe.
2065      *
2066      * @param messageClass   The message type.
2067      * @param builderClass   The builder type.
2068      * @return this
2069      */
2070     public FieldAccessorTable ensureFieldAccessorsInitialized(
2071         Class<? extends GeneratedMessage> messageClass,
2072         Class<? extends Builder> builderClass) {
2073       if (initialized) { return this; }
2074       synchronized (this) {
2075         if (initialized) { return this; }
2076         int fieldsSize = fields.length;
2077         for (int i = 0; i < fieldsSize; i++) {
2078           FieldDescriptor field = descriptor.getFields().get(i);
2079           String containingOneofCamelCaseName = null;
2080           if (field.getContainingOneof() != null) {
2081             containingOneofCamelCaseName =
2082                 camelCaseNames[fieldsSize + field.getContainingOneof().getIndex()];
2083           }
2084           if (field.isRepeated()) {
2085             if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
2086               if (field.isMapField() && isMapFieldEnabled(field)) {
2087                 fields[i] = new MapFieldAccessor(
2088                     field, camelCaseNames[i], messageClass, builderClass);
2089               } else {
2090                 fields[i] = new RepeatedMessageFieldAccessor(
2091                     field, camelCaseNames[i], messageClass, builderClass);
2092               }
2093             } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) {
2094               fields[i] = new RepeatedEnumFieldAccessor(
2095                   field, camelCaseNames[i], messageClass, builderClass);
2096             } else {
2097               fields[i] = new RepeatedFieldAccessor(
2098                   field, camelCaseNames[i], messageClass, builderClass);
2099             }
2100           } else {
2101             if (field.getJavaType() == FieldDescriptor.JavaType.MESSAGE) {
2102               fields[i] = new SingularMessageFieldAccessor(
2103                   field, camelCaseNames[i], messageClass, builderClass,
2104                   containingOneofCamelCaseName);
2105             } else if (field.getJavaType() == FieldDescriptor.JavaType.ENUM) {
2106               fields[i] = new SingularEnumFieldAccessor(
2107                   field, camelCaseNames[i], messageClass, builderClass,
2108                   containingOneofCamelCaseName);
2109             } else if (field.getJavaType() == FieldDescriptor.JavaType.STRING) {
2110               fields[i] = new SingularStringFieldAccessor(
2111                   field, camelCaseNames[i], messageClass, builderClass,
2112                   containingOneofCamelCaseName);
2113             } else {
2114               fields[i] = new SingularFieldAccessor(
2115                   field, camelCaseNames[i], messageClass, builderClass,
2116                   containingOneofCamelCaseName);
2117             }
2118           }
2119         }
2120 
2121         int oneofsSize = oneofs.length;
2122         for (int i = 0; i < oneofsSize; i++) {
2123           oneofs[i] = new OneofAccessor(
2124               descriptor, camelCaseNames[i + fieldsSize],
2125               messageClass, builderClass);
2126         }
2127         initialized = true;
2128         camelCaseNames = null;
2129         return this;
2130       }
2131     }
2132 
2133     private final Descriptor descriptor;
2134     private final FieldAccessor[] fields;
2135     private String[] camelCaseNames;
2136     private final OneofAccessor[] oneofs;
2137     private volatile boolean initialized;
2138 
2139     /** Get the FieldAccessor for a particular field. */
2140     private FieldAccessor getField(final FieldDescriptor field) {
2141       if (field.getContainingType() != descriptor) {
2142         throw new IllegalArgumentException(
2143           "FieldDescriptor does not match message type.");
2144       } else if (field.isExtension()) {
2145         // If this type had extensions, it would subclass ExtendableMessage,
2146         // which overrides the reflection interface to handle extensions.
2147         throw new IllegalArgumentException(
2148           "This type does not have extensions.");
2149       }
2150       return fields[field.getIndex()];
2151     }
2152 
2153     /** Get the OneofAccessor for a particular oneof. */
2154     private OneofAccessor getOneof(final OneofDescriptor oneof) {
2155       if (oneof.getContainingType() != descriptor) {
2156         throw new IllegalArgumentException(
2157           "OneofDescriptor does not match message type.");
2158       }
2159       return oneofs[oneof.getIndex()];
2160     }
2161 
2162     /**
2163      * Abstract interface that provides access to a single field.  This is
2164      * implemented differently depending on the field type and cardinality.
2165      */
2166     private interface FieldAccessor {
2167       Object get(GeneratedMessage message);
2168       Object get(GeneratedMessage.Builder builder);
2169       Object getRaw(GeneratedMessage message);
2170       Object getRaw(GeneratedMessage.Builder builder);
2171       void set(Builder builder, Object value);
2172       Object getRepeated(GeneratedMessage message, int index);
2173       Object getRepeated(GeneratedMessage.Builder builder, int index);
2174       Object getRepeatedRaw(GeneratedMessage message, int index);
2175       Object getRepeatedRaw(GeneratedMessage.Builder builder, int index);
2176       void setRepeated(Builder builder,
2177                        int index, Object value);
2178       void addRepeated(Builder builder, Object value);
2179       boolean has(GeneratedMessage message);
2180       boolean has(GeneratedMessage.Builder builder);
2181       int getRepeatedCount(GeneratedMessage message);
2182       int getRepeatedCount(GeneratedMessage.Builder builder);
2183       void clear(Builder builder);
2184       Message.Builder newBuilder();
2185       Message.Builder getBuilder(GeneratedMessage.Builder builder);
2186       Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder,
2187                                          int index);
2188     }
2189 
2190     /** OneofAccessor provides access to a single oneof. */
2191     private static class OneofAccessor {
2192       OneofAccessor(
2193           final Descriptor descriptor, final String camelCaseName,
2194           final Class<? extends GeneratedMessage> messageClass,
2195           final Class<? extends Builder> builderClass) {
2196         this.descriptor = descriptor;
2197         caseMethod =
2198             getMethodOrDie(messageClass, "get" + camelCaseName + "Case");
2199         caseMethodBuilder =
2200             getMethodOrDie(builderClass, "get" + camelCaseName + "Case");
2201         clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
2202       }
2203 
2204       private final Descriptor descriptor;
2205       private final Method caseMethod;
2206       private final Method caseMethodBuilder;
2207       private final Method clearMethod;
2208 
2209       public boolean has(final GeneratedMessage message) {
2210         if (((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber() == 0) {
2211           return false;
2212         }
2213         return true;
2214       }
2215 
2216       public boolean has(GeneratedMessage.Builder builder) {
2217         if (((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber() == 0) {
2218           return false;
2219         }
2220         return true;
2221       }
2222 
2223       public FieldDescriptor get(final GeneratedMessage message) {
2224         int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber();
2225         if (fieldNumber > 0) {
2226           return descriptor.findFieldByNumber(fieldNumber);
2227         }
2228         return null;
2229       }
2230 
2231       public FieldDescriptor get(GeneratedMessage.Builder builder) {
2232         int fieldNumber = ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber();
2233         if (fieldNumber > 0) {
2234           return descriptor.findFieldByNumber(fieldNumber);
2235         }
2236         return null;
2237       }
2238 
2239       public void clear(final Builder builder) {
2240         invokeOrDie(clearMethod, builder);
2241       }
2242     }
2243 
2244     private static boolean supportFieldPresence(FileDescriptor file) {
2245       return file.getSyntax() == FileDescriptor.Syntax.PROTO2;
2246     }
2247 
2248     // ---------------------------------------------------------------
2249 
2250     private static class SingularFieldAccessor implements FieldAccessor {
2251       SingularFieldAccessor(
2252           final FieldDescriptor descriptor, final String camelCaseName,
2253           final Class<? extends GeneratedMessage> messageClass,
2254           final Class<? extends Builder> builderClass,
2255           final String containingOneofCamelCaseName) {
2256         field = descriptor;
2257         isOneofField = descriptor.getContainingOneof() != null;
2258         hasHasMethod = supportFieldPresence(descriptor.getFile())
2259             || (!isOneofField && descriptor.getJavaType() == FieldDescriptor.JavaType.MESSAGE);
2260         getMethod = getMethodOrDie(messageClass, "get" + camelCaseName);
2261         getMethodBuilder = getMethodOrDie(builderClass, "get" + camelCaseName);
2262         type = getMethod.getReturnType();
2263         setMethod = getMethodOrDie(builderClass, "set" + camelCaseName, type);
2264         hasMethod =
2265             hasHasMethod ? getMethodOrDie(messageClass, "has" + camelCaseName) : null;
2266         hasMethodBuilder =
2267             hasHasMethod ? getMethodOrDie(builderClass, "has" + camelCaseName) : null;
2268         clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
2269         caseMethod = isOneofField ? getMethodOrDie(
2270             messageClass, "get" + containingOneofCamelCaseName + "Case") : null;
2271         caseMethodBuilder = isOneofField ? getMethodOrDie(
2272             builderClass, "get" + containingOneofCamelCaseName + "Case") : null;
2273       }
2274 
2275       // Note:  We use Java reflection to call public methods rather than
2276       //   access private fields directly as this avoids runtime security
2277       //   checks.
2278       protected final Class<?> type;
2279       protected final Method getMethod;
2280       protected final Method getMethodBuilder;
2281       protected final Method setMethod;
2282       protected final Method hasMethod;
2283       protected final Method hasMethodBuilder;
2284       protected final Method clearMethod;
2285       protected final Method caseMethod;
2286       protected final Method caseMethodBuilder;
2287       protected final FieldDescriptor field;
2288       protected final boolean isOneofField;
2289       protected final boolean hasHasMethod;
2290 
2291       private int getOneofFieldNumber(final GeneratedMessage message) {
2292         return ((Internal.EnumLite) invokeOrDie(caseMethod, message)).getNumber();
2293       }
2294 
2295       private int getOneofFieldNumber(final GeneratedMessage.Builder builder) {
2296         return ((Internal.EnumLite) invokeOrDie(caseMethodBuilder, builder)).getNumber();
2297       }
2298 
2299       @Override
2300       public Object get(final GeneratedMessage message) {
2301         return invokeOrDie(getMethod, message);
2302       }
2303       @Override
2304       public Object get(GeneratedMessage.Builder builder) {
2305         return invokeOrDie(getMethodBuilder, builder);
2306       }
2307       @Override
2308       public Object getRaw(final GeneratedMessage message) {
2309         return get(message);
2310       }
2311       @Override
2312       public Object getRaw(GeneratedMessage.Builder builder) {
2313         return get(builder);
2314       }
2315       @Override
2316       public void set(final Builder builder, final Object value) {
2317         invokeOrDie(setMethod, builder, value);
2318       }
2319       @Override
2320       public Object getRepeated(final GeneratedMessage message, final int index) {
2321         throw new UnsupportedOperationException(
2322           "getRepeatedField() called on a singular field.");
2323       }
2324       @Override
2325       public Object getRepeatedRaw(final GeneratedMessage message, final int index) {
2326         throw new UnsupportedOperationException(
2327           "getRepeatedFieldRaw() called on a singular field.");
2328       }
2329       @Override
2330       public Object getRepeated(GeneratedMessage.Builder builder, int index) {
2331         throw new UnsupportedOperationException(
2332           "getRepeatedField() called on a singular field.");
2333       }
2334       @Override
2335       public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) {
2336         throw new UnsupportedOperationException(
2337           "getRepeatedFieldRaw() called on a singular field.");
2338       }
2339       @Override
2340       public void setRepeated(final Builder builder, final int index, final Object value) {
2341         throw new UnsupportedOperationException(
2342           "setRepeatedField() called on a singular field.");
2343       }
2344       @Override
2345       public void addRepeated(final Builder builder, final Object value) {
2346         throw new UnsupportedOperationException(
2347           "addRepeatedField() called on a singular field.");
2348       }
2349       @Override
2350       public boolean has(final GeneratedMessage message) {
2351         if (!hasHasMethod) {
2352           if (isOneofField) {
2353             return getOneofFieldNumber(message) == field.getNumber();
2354           }
2355           return !get(message).equals(field.getDefaultValue());
2356         }
2357         return (Boolean) invokeOrDie(hasMethod, message);
2358       }
2359       @Override
2360       public boolean has(GeneratedMessage.Builder builder) {
2361         if (!hasHasMethod) {
2362           if (isOneofField) {
2363             return getOneofFieldNumber(builder) == field.getNumber();
2364           }
2365           return !get(builder).equals(field.getDefaultValue());
2366         }
2367         return (Boolean) invokeOrDie(hasMethodBuilder, builder);
2368       }
2369       @Override
2370       public int getRepeatedCount(final GeneratedMessage message) {
2371         throw new UnsupportedOperationException(
2372           "getRepeatedFieldSize() called on a singular field.");
2373       }
2374       @Override
2375       public int getRepeatedCount(GeneratedMessage.Builder builder) {
2376         throw new UnsupportedOperationException(
2377           "getRepeatedFieldSize() called on a singular field.");
2378       }
2379       @Override
2380       public void clear(final Builder builder) {
2381         invokeOrDie(clearMethod, builder);
2382       }
2383       @Override
2384       public Message.Builder newBuilder() {
2385         throw new UnsupportedOperationException(
2386           "newBuilderForField() called on a non-Message type.");
2387       }
2388       @Override
2389       public Message.Builder getBuilder(GeneratedMessage.Builder builder) {
2390         throw new UnsupportedOperationException(
2391           "getFieldBuilder() called on a non-Message type.");
2392       }
2393       @Override
2394       public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) {
2395         throw new UnsupportedOperationException(
2396           "getRepeatedFieldBuilder() called on a non-Message type.");
2397       }
2398     }
2399 
2400     private static class RepeatedFieldAccessor implements FieldAccessor {
2401       protected final Class type;
2402       protected final Method getMethod;
2403       protected final Method getMethodBuilder;
2404       protected final Method getRepeatedMethod;
2405       protected final Method getRepeatedMethodBuilder;
2406       protected final Method setRepeatedMethod;
2407       protected final Method addRepeatedMethod;
2408       protected final Method getCountMethod;
2409       protected final Method getCountMethodBuilder;
2410       protected final Method clearMethod;
2411 
2412       RepeatedFieldAccessor(
2413           final FieldDescriptor descriptor, final String camelCaseName,
2414           final Class<? extends GeneratedMessage> messageClass,
2415           final Class<? extends Builder> builderClass) {
2416         getMethod = getMethodOrDie(messageClass,
2417                                    "get" + camelCaseName + "List");
2418         getMethodBuilder = getMethodOrDie(builderClass,
2419                                    "get" + camelCaseName + "List");
2420         getRepeatedMethod =
2421             getMethodOrDie(messageClass, "get" + camelCaseName, Integer.TYPE);
2422         getRepeatedMethodBuilder =
2423             getMethodOrDie(builderClass, "get" + camelCaseName, Integer.TYPE);
2424         type = getRepeatedMethod.getReturnType();
2425         setRepeatedMethod =
2426             getMethodOrDie(builderClass, "set" + camelCaseName,
2427                            Integer.TYPE, type);
2428         addRepeatedMethod =
2429             getMethodOrDie(builderClass, "add" + camelCaseName, type);
2430         getCountMethod =
2431             getMethodOrDie(messageClass, "get" + camelCaseName + "Count");
2432         getCountMethodBuilder =
2433             getMethodOrDie(builderClass, "get" + camelCaseName + "Count");
2434 
2435         clearMethod = getMethodOrDie(builderClass, "clear" + camelCaseName);
2436       }
2437 
2438       @Override
2439       public Object get(final GeneratedMessage message) {
2440         return invokeOrDie(getMethod, message);
2441       }
2442       @Override
2443       public Object get(GeneratedMessage.Builder builder) {
2444         return invokeOrDie(getMethodBuilder, builder);
2445       }
2446       @Override
2447       public Object getRaw(final GeneratedMessage message) {
2448         return get(message);
2449       }
2450       @Override
2451       public Object getRaw(GeneratedMessage.Builder builder) {
2452         return get(builder);
2453       }
2454       @Override
2455       public void set(final Builder builder, final Object value) {
2456         // Add all the elements individually.  This serves two purposes:
2457         // 1) Verifies that each element has the correct type.
2458         // 2) Insures that the caller cannot modify the list later on and
2459         //    have the modifications be reflected in the message.
2460         clear(builder);
2461         for (final Object element : (List<?>) value) {
2462           addRepeated(builder, element);
2463         }
2464       }
2465       @Override
2466       public Object getRepeated(final GeneratedMessage message, final int index) {
2467         return invokeOrDie(getRepeatedMethod, message, index);
2468       }
2469       @Override
2470       public Object getRepeated(GeneratedMessage.Builder builder, int index) {
2471         return invokeOrDie(getRepeatedMethodBuilder, builder, index);
2472       }
2473       @Override
2474       public Object getRepeatedRaw(GeneratedMessage message, int index) {
2475         return getRepeated(message, index);
2476       }
2477       @Override
2478       public Object getRepeatedRaw(GeneratedMessage.Builder builder, int index) {
2479         return getRepeated(builder, index);
2480       }
2481       @Override
2482       public void setRepeated(final Builder builder, final int index, final Object value) {
2483         invokeOrDie(setRepeatedMethod, builder, index, value);
2484       }
2485       @Override
2486       public void addRepeated(final Builder builder, final Object value) {
2487         invokeOrDie(addRepeatedMethod, builder, value);
2488       }
2489       @Override
2490       public boolean has(final GeneratedMessage message) {
2491         throw new UnsupportedOperationException(
2492           "hasField() called on a repeated field.");
2493       }
2494       @Override
2495       public boolean has(GeneratedMessage.Builder builder) {
2496         throw new UnsupportedOperationException(
2497           "hasField() called on a repeated field.");
2498       }
2499       @Override
2500       public int getRepeatedCount(final GeneratedMessage message) {
2501         return (Integer) invokeOrDie(getCountMethod, message);
2502       }
2503       @Override
2504       public int getRepeatedCount(GeneratedMessage.Builder builder) {
2505         return (Integer) invokeOrDie(getCountMethodBuilder, builder);
2506       }
2507       @Override
2508       public void clear(final Builder builder) {
2509         invokeOrDie(clearMethod, builder);
2510       }
2511       @Override
2512       public Message.Builder newBuilder() {
2513         throw new UnsupportedOperationException(
2514           "newBuilderForField() called on a non-Message type.");
2515       }
2516       @Override
2517       public Message.Builder getBuilder(GeneratedMessage.Builder builder) {
2518         throw new UnsupportedOperationException(
2519           "getFieldBuilder() called on a non-Message type.");
2520       }
2521       @Override
2522       public Message.Builder getRepeatedBuilder(GeneratedMessage.Builder builder, int index) {
2523         throw new UnsupportedOperationException(
2524           "getRepeatedFieldBuilder() called on a non-Message type.");
2525       }
2526     }
2527 
2528     private static class MapFieldAccessor implements FieldAccessor {
2529       MapFieldAccessor(
2530           final FieldDescriptor descriptor, final String camelCaseName,
2531           final Class<? extends GeneratedMessage> messageClass,
2532           final Class<? extends Builder> builderClass) {
2533         field = descriptor;
2534         Method getDefaultInstanceMethod =
2535             getMethodOrDie(messageClass, "getDefaultInstance");
2536         MapField defaultMapField = getMapField(
2537             (GeneratedMessage) invokeOrDie(getDefaultInstanceMethod, null));
2538         mapEntryMessageDefaultInstance =
2539             defaultMapField.getMapEntryMessageDefaultInstance();
2540       }
2541 
2542       private final FieldDescriptor field;
2543       private final Message mapEntryMessageDefaultInstance;
2544 
2545       private MapField<?, ?> getMapField(GeneratedMessage message) {
2546         return (MapField<?, ?>) message.internalGetMapField(field.getNumber());
2547       }
2548 
2549       private MapField<?, ?> getMapField(GeneratedMessage.Builder builder) {
2550         return (MapField<?, ?>) builder.internalGetMapField(field.getNumber());
2551       }
2552 
2553       private MapField<?, ?> getMutableMapField(
2554           GeneratedMessage.Builder builder) {
2555         return (MapField<?, ?>) builder.internalGetMutableMapField(
2556             field.getNumber());
2557       }
2558 
2559       @Override
2560       @SuppressWarnings("unchecked")
2561       public Object get(GeneratedMessage message) {
2562         List result = new ArrayList();
2563         for (int i = 0; i < getRepeatedCount(message); i++) {
2564           result.add(getRepeated(message, i));
2565         }
2566         return Collections.unmodifiableList(result);
2567       }
2568 
2569       @Override
2570       @SuppressWarnings("unchecked")
2571       public Object get(Builder builder) {
2572         List result = new ArrayList();
2573         for (int i = 0; i < getRepeatedCount(builder); i++) {
2574           result.add(getRepeated(builder, i));
2575         }
2576         return Collections.unmodifiableList(result);
2577       }
2578 
2579       @Override
2580       public Object getRaw(GeneratedMessage message) {
2581         return get(message);
2582       }
2583 
2584       @Override
2585       public Object getRaw(GeneratedMessage.Builder builder) {
2586         return get(builder);
2587       }
2588 
2589       @Override
2590       public void set(Builder builder, Object value) {
2591         clear(builder);
2592         for (Object entry : (List) value) {
2593           addRepeated(builder, entry);
2594         }
2595       }
2596 
2597       @Override
2598       public Object getRepeated(GeneratedMessage message, int index) {
2599         return getMapField(message).getList().get(index);
2600       }
2601 
2602       @Override
2603       public Object getRepeated(Builder builder, int index) {
2604         return getMapField(builder).getList().get(index);
2605       }
2606 
2607       @Override
2608       public Object getRepeatedRaw(GeneratedMessage message, int index) {
2609         return getRepeated(message, index);
2610       }
2611 
2612       @Override
2613       public Object getRepeatedRaw(Builder builder, int index) {
2614         return getRepeated(builder, index);
2615       }
2616 
2617       @Override
2618       public void setRepeated(Builder builder, int index, Object value) {
2619         getMutableMapField(builder).getMutableList().set(index, (Message) value);
2620       }
2621 
2622       @Override
2623       public void addRepeated(Builder builder, Object value) {
2624         getMutableMapField(builder).getMutableList().add((Message) value);
2625       }
2626 
2627       @Override
2628       public boolean has(GeneratedMessage message) {
2629         throw new UnsupportedOperationException(
2630             "hasField() is not supported for repeated fields.");
2631       }
2632 
2633       @Override
2634       public boolean has(Builder builder) {
2635         throw new UnsupportedOperationException(
2636             "hasField() is not supported for repeated fields.");
2637       }
2638 
2639       @Override
2640       public int getRepeatedCount(GeneratedMessage message) {
2641         return getMapField(message).getList().size();
2642       }
2643 
2644       @Override
2645       public int getRepeatedCount(Builder builder) {
2646         return getMapField(builder).getList().size();
2647       }
2648 
2649       @Override
2650       public void clear(Builder builder) {
2651         getMutableMapField(builder).getMutableList().clear();
2652       }
2653 
2654       @Override
2655       public com.google.protobuf.Message.Builder newBuilder() {
2656         return mapEntryMessageDefaultInstance.newBuilderForType();
2657       }
2658 
2659       @Override
2660       public com.google.protobuf.Message.Builder getBuilder(Builder builder) {
2661         throw new UnsupportedOperationException(
2662             "Nested builder not supported for map fields.");
2663       }
2664 
2665       @Override
2666       public com.google.protobuf.Message.Builder getRepeatedBuilder(Builder builder, int index) {
2667         throw new UnsupportedOperationException(
2668             "Nested builder not supported for map fields.");
2669       }
2670     }
2671 
2672     // ---------------------------------------------------------------
2673 
2674     private static final class SingularEnumFieldAccessor
2675         extends SingularFieldAccessor {
2676       SingularEnumFieldAccessor(
2677           final FieldDescriptor descriptor, final String camelCaseName,
2678           final Class<? extends GeneratedMessage> messageClass,
2679           final Class<? extends Builder> builderClass,
2680           final String containingOneofCamelCaseName) {
2681         super(descriptor, camelCaseName, messageClass, builderClass, containingOneofCamelCaseName);
2682 
2683         enumDescriptor = descriptor.getEnumType();
2684 
2685         valueOfMethod = getMethodOrDie(type, "valueOf",
2686                                        EnumValueDescriptor.class);
2687         getValueDescriptorMethod =
2688           getMethodOrDie(type, "getValueDescriptor");
2689 
2690         supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue();
2691         if (supportUnknownEnumValue) {
2692           getValueMethod =
2693               getMethodOrDie(messageClass, "get" + camelCaseName + "Value");
2694           getValueMethodBuilder =
2695               getMethodOrDie(builderClass, "get" + camelCaseName + "Value");
2696           setValueMethod =
2697               getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class);
2698         }
2699       }
2700 
2701       private EnumDescriptor enumDescriptor;
2702 
2703       private Method valueOfMethod;
2704       private Method getValueDescriptorMethod;
2705 
2706       private boolean supportUnknownEnumValue;
2707       private Method getValueMethod;
2708       private Method getValueMethodBuilder;
2709       private Method setValueMethod;
2710 
2711       @Override
2712       public Object get(final GeneratedMessage message) {
2713         if (supportUnknownEnumValue) {
2714           int value = (Integer) invokeOrDie(getValueMethod, message);
2715           return enumDescriptor.findValueByNumberCreatingIfUnknown(value);
2716         }
2717         return invokeOrDie(getValueDescriptorMethod, super.get(message));
2718       }
2719 
2720       @Override
2721       public Object get(final GeneratedMessage.Builder builder) {
2722         if (supportUnknownEnumValue) {
2723           int value = (Integer) invokeOrDie(getValueMethodBuilder, builder);
2724           return enumDescriptor.findValueByNumberCreatingIfUnknown(value);
2725         }
2726         return invokeOrDie(getValueDescriptorMethod, super.get(builder));
2727       }
2728 
2729       @Override
2730       public void set(final Builder builder, final Object value) {
2731         if (supportUnknownEnumValue) {
2732           invokeOrDie(setValueMethod, builder,
2733               ((EnumValueDescriptor) value).getNumber());
2734           return;
2735         }
2736         super.set(builder, invokeOrDie(valueOfMethod, null, value));
2737       }
2738     }
2739 
2740     private static final class RepeatedEnumFieldAccessor
2741         extends RepeatedFieldAccessor {
2742       RepeatedEnumFieldAccessor(
2743           final FieldDescriptor descriptor, final String camelCaseName,
2744           final Class<? extends GeneratedMessage> messageClass,
2745           final Class<? extends Builder> builderClass) {
2746         super(descriptor, camelCaseName, messageClass, builderClass);
2747 
2748         enumDescriptor = descriptor.getEnumType();
2749 
2750         valueOfMethod = getMethodOrDie(type, "valueOf",
2751                                        EnumValueDescriptor.class);
2752         getValueDescriptorMethod =
2753           getMethodOrDie(type, "getValueDescriptor");
2754 
2755         supportUnknownEnumValue = descriptor.getFile().supportsUnknownEnumValue();
2756         if (supportUnknownEnumValue) {
2757           getRepeatedValueMethod =
2758               getMethodOrDie(messageClass, "get" + camelCaseName + "Value", int.class);
2759           getRepeatedValueMethodBuilder =
2760               getMethodOrDie(builderClass, "get" + camelCaseName + "Value", int.class);
2761           setRepeatedValueMethod =
2762               getMethodOrDie(builderClass, "set" + camelCaseName + "Value", int.class, int.class);
2763           addRepeatedValueMethod =
2764               getMethodOrDie(builderClass, "add" + camelCaseName + "Value", int.class);
2765         }
2766       }
2767       private EnumDescriptor enumDescriptor;
2768 
2769       private final Method valueOfMethod;
2770       private final Method getValueDescriptorMethod;
2771 
2772       private boolean supportUnknownEnumValue;
2773       private Method getRepeatedValueMethod;
2774       private Method getRepeatedValueMethodBuilder;
2775       private Method setRepeatedValueMethod;
2776       private Method addRepeatedValueMethod;
2777 
2778       @Override
2779       @SuppressWarnings("unchecked")
2780       public Object get(final GeneratedMessage message) {
2781         final List newList = new ArrayList();
2782         final int size = getRepeatedCount(message);
2783         for (int i = 0; i < size; i++) {
2784           newList.add(getRepeated(message, i));
2785         }
2786         return Collections.unmodifiableList(newList);
2787       }
2788 
2789       @Override
2790       @SuppressWarnings("unchecked")
2791       public Object get(final GeneratedMessage.Builder builder) {
2792         final List newList = new ArrayList();
2793         final int size = getRepeatedCount(builder);
2794         for (int i = 0; i < size; i++) {
2795           newList.add(getRepeated(builder, i));
2796         }
2797         return Collections.unmodifiableList(newList);
2798       }
2799 
2800       @Override
2801       public Object getRepeated(final GeneratedMessage message,
2802                                 final int index) {
2803         if (supportUnknownEnumValue) {
2804           int value = (Integer) invokeOrDie(getRepeatedValueMethod, message, index);
2805           return enumDescriptor.findValueByNumberCreatingIfUnknown(value);
2806         }
2807         return invokeOrDie(getValueDescriptorMethod,
2808           super.getRepeated(message, index));
2809       }
2810       @Override
2811       public Object getRepeated(final GeneratedMessage.Builder builder,
2812                                 final int index) {
2813         if (supportUnknownEnumValue) {
2814           int value = (Integer) invokeOrDie(getRepeatedValueMethodBuilder, builder, index);
2815           return enumDescriptor.findValueByNumberCreatingIfUnknown(value);
2816         }
2817         return invokeOrDie(getValueDescriptorMethod,
2818           super.getRepeated(builder, index));
2819       }
2820       @Override
2821       public void setRepeated(final Builder builder,
2822                               final int index, final Object value) {
2823         if (supportUnknownEnumValue) {
2824           invokeOrDie(setRepeatedValueMethod, builder, index,
2825               ((EnumValueDescriptor) value).getNumber());
2826           return;
2827         }
2828         super.setRepeated(builder, index, invokeOrDie(valueOfMethod, null,
2829                           value));
2830       }
2831       @Override
2832       public void addRepeated(final Builder builder, final Object value) {
2833         if (supportUnknownEnumValue) {
2834           invokeOrDie(addRepeatedValueMethod, builder,
2835               ((EnumValueDescriptor) value).getNumber());
2836           return;
2837         }
2838         super.addRepeated(builder, invokeOrDie(valueOfMethod, null, value));
2839       }
2840     }
2841 
2842     // ---------------------------------------------------------------
2843 
2844     /**
2845      * Field accessor for string fields.
2846      *
2847      * <p>This class makes getFooBytes() and setFooBytes() available for
2848      * reflection API so that reflection based serialize/parse functions can
2849      * access the raw bytes of the field to preserve non-UTF8 bytes in the
2850      * string.
2851      *
2852      * <p>This ensures the serialize/parse round-trip safety, which is important
2853      * for servers which forward messages.
2854      */
2855     private static final class SingularStringFieldAccessor
2856         extends SingularFieldAccessor {
2857       SingularStringFieldAccessor(
2858           final FieldDescriptor descriptor, final String camelCaseName,
2859           final Class<? extends GeneratedMessage> messageClass,
2860           final Class<? extends Builder> builderClass,
2861           final String containingOneofCamelCaseName) {
2862         super(descriptor, camelCaseName, messageClass, builderClass,
2863             containingOneofCamelCaseName);
2864         getBytesMethod = getMethodOrDie(messageClass,
2865             "get" + camelCaseName + "Bytes");
2866         getBytesMethodBuilder = getMethodOrDie(builderClass,
2867             "get" + camelCaseName + "Bytes");
2868         setBytesMethodBuilder = getMethodOrDie(builderClass,
2869             "set" + camelCaseName + "Bytes", ByteString.class);
2870       }
2871 
2872       private final Method getBytesMethod;
2873       private final Method getBytesMethodBuilder;
2874       private final Method setBytesMethodBuilder;
2875 
2876       @Override
2877       public Object getRaw(final GeneratedMessage message) {
2878         return invokeOrDie(getBytesMethod, message);
2879       }
2880 
2881       @Override
2882       public Object getRaw(GeneratedMessage.Builder builder) {
2883         return invokeOrDie(getBytesMethodBuilder, builder);
2884       }
2885 
2886       @Override
2887       public void set(GeneratedMessage.Builder builder, Object value) {
2888         if (value instanceof ByteString) {
2889           invokeOrDie(setBytesMethodBuilder, builder, value);
2890         } else {
2891           super.set(builder, value);
2892         }
2893       }
2894     }
2895 
2896     // ---------------------------------------------------------------
2897 
2898     private static final class SingularMessageFieldAccessor
2899         extends SingularFieldAccessor {
2900       SingularMessageFieldAccessor(
2901           final FieldDescriptor descriptor, final String camelCaseName,
2902           final Class<? extends GeneratedMessage> messageClass,
2903           final Class<? extends Builder> builderClass,
2904           final String containingOneofCamelCaseName) {
2905         super(descriptor, camelCaseName, messageClass, builderClass,
2906             containingOneofCamelCaseName);
2907 
2908         newBuilderMethod = getMethodOrDie(type, "newBuilder");
2909         getBuilderMethodBuilder =
2910             getMethodOrDie(builderClass, "get" + camelCaseName + "Builder");
2911       }
2912 
2913       private final Method newBuilderMethod;
2914       private final Method getBuilderMethodBuilder;
2915 
2916       private Object coerceType(final Object value) {
2917         if (type.isInstance(value)) {
2918           return value;
2919         } else {
2920           // The value is not the exact right message type.  However, if it
2921           // is an alternative implementation of the same type -- e.g. a
2922           // DynamicMessage -- we should accept it.  In this case we can make
2923           // a copy of the message.
2924           return ((Message.Builder) invokeOrDie(newBuilderMethod, null))
2925                   .mergeFrom((Message) value).buildPartial();
2926         }
2927       }
2928 
2929       @Override
2930       public void set(final Builder builder, final Object value) {
2931         super.set(builder, coerceType(value));
2932       }
2933       @Override
2934       public Message.Builder newBuilder() {
2935         return (Message.Builder) invokeOrDie(newBuilderMethod, null);
2936       }
2937       @Override
2938       public Message.Builder getBuilder(GeneratedMessage.Builder builder) {
2939         return (Message.Builder) invokeOrDie(getBuilderMethodBuilder, builder);
2940       }
2941     }
2942 
2943     private static final class RepeatedMessageFieldAccessor
2944         extends RepeatedFieldAccessor {
2945       RepeatedMessageFieldAccessor(
2946           final FieldDescriptor descriptor, final String camelCaseName,
2947           final Class<? extends GeneratedMessage> messageClass,
2948           final Class<? extends Builder> builderClass) {
2949         super(descriptor, camelCaseName, messageClass, builderClass);
2950 
2951         newBuilderMethod = getMethodOrDie(type, "newBuilder");
2952         getBuilderMethodBuilder = getMethodOrDie(builderClass,
2953             "get" + camelCaseName + "Builder", Integer.TYPE);
2954       }
2955 
2956       private final Method newBuilderMethod;
2957       private final Method getBuilderMethodBuilder;
2958 
2959       private Object coerceType(final Object value) {
2960         if (type.isInstance(value)) {
2961           return value;
2962         } else {
2963           // The value is not the exact right message type.  However, if it
2964           // is an alternative implementation of the same type -- e.g. a
2965           // DynamicMessage -- we should accept it.  In this case we can make
2966           // a copy of the message.
2967           return ((Message.Builder) invokeOrDie(newBuilderMethod, null))
2968                   .mergeFrom((Message) value).build();
2969         }
2970       }
2971 
2972       @Override
2973       public void setRepeated(final Builder builder,
2974                               final int index, final Object value) {
2975         super.setRepeated(builder, index, coerceType(value));
2976       }
2977       @Override
2978       public void addRepeated(final Builder builder, final Object value) {
2979         super.addRepeated(builder, coerceType(value));
2980       }
2981       @Override
2982       public Message.Builder newBuilder() {
2983         return (Message.Builder) invokeOrDie(newBuilderMethod, null);
2984       }
2985       @Override
2986       public Message.Builder getRepeatedBuilder(
2987           final GeneratedMessage.Builder builder, final int index) {
2988         return (Message.Builder) invokeOrDie(
2989             getBuilderMethodBuilder, builder, index);
2990       }
2991     }
2992   }
2993 
2994   /**
2995    * Replaces this object in the output stream with a serialized form.
2996    * Part of Java's serialization magic.  Generated sub-classes must override
2997    * this method by calling {@code return super.writeReplace();}
2998    * @return a SerializedForm of this message
2999    */
3000   protected Object writeReplace() throws ObjectStreamException {
3001     return new GeneratedMessageLite.SerializedForm(this);
3002   }
3003 
3004   /**
3005    * Checks that the {@link Extension} is non-Lite and returns it as a
3006    * {@link GeneratedExtension}.
3007    */
3008   private static <MessageType extends ExtendableMessage<MessageType>, T>
3009     Extension<MessageType, T> checkNotLite(
3010         ExtensionLite<MessageType, T> extension) {
3011     if (extension.isLite()) {
3012       throw new IllegalArgumentException("Expected non-lite extension.");
3013     }
3014 
3015     return (Extension<MessageType, T>) extension;
3016   }
3017 
3018   protected static int computeStringSize(final int fieldNumber, final Object value) {
3019     if (value instanceof String) {
3020       return CodedOutputStream.computeStringSize(fieldNumber, (String) value);
3021     } else {
3022       return CodedOutputStream.computeBytesSize(fieldNumber, (ByteString) value);
3023     }
3024   }
3025 
3026   protected static int computeStringSizeNoTag(final Object value) {
3027     if (value instanceof String) {
3028       return CodedOutputStream.computeStringSizeNoTag((String) value);
3029     } else {
3030       return CodedOutputStream.computeBytesSizeNoTag((ByteString) value);
3031     }
3032   }
3033 
3034   protected static void writeString(
3035       CodedOutputStream output, final int fieldNumber, final Object value) throws IOException {
3036     if (value instanceof String) {
3037       output.writeString(fieldNumber, (String) value);
3038     } else {
3039       output.writeBytes(fieldNumber, (ByteString) value);
3040     }
3041   }
3042 
3043   protected static void writeStringNoTag(
3044       CodedOutputStream output, final Object value) throws IOException {
3045     if (value instanceof String) {
3046       output.writeStringNoTag((String) value);
3047     } else {
3048       output.writeBytesNoTag((ByteString) value);
3049     }
3050   }
3051 }
3052