aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorÉamonn McManus <emcmanus@google.com>2016-04-05 13:15:51 -0700
committerÉamonn McManus <emcmanus@google.com>2016-04-05 13:15:51 -0700
commit953d94024dcca49acd4fdbf4ffe00b530226c4f8 (patch)
tree2646256f3ecc2d10af78cbd6477d2fc4a3a04fe6
parent230a8e697654e285b5218a293b5a74701f5c806d (diff)
parent1639603434a38815e06ee938f9ada1e957be3498 (diff)
downloadauto-953d94024dcca49acd4fdbf4ffe00b530226c4f8.tar.gz
Merge pull request #317 from google/moe_writing_branch_from_9084efc327fad709db7e72f9fa20c5feacde395a
Moe writing branch from 9084efc327fad709db7e72f9fa20c5feacde395a
-rw-r--r--README.md41
-rw-r--r--value/CHANGES.md59
-rw-r--r--value/README.md554
-rw-r--r--value/src/it/functional/pom.xml5
-rw-r--r--value/src/test/java/com/google/auto/value/processor/GuavaCollectionBuildersTest.java2
-rw-r--r--value/userguide/builders-howto.md22
-rw-r--r--value/userguide/builders.md13
-rw-r--r--value/userguide/howto.md44
-rw-r--r--value/userguide/index.md38
-rw-r--r--value/userguide/performance.md2
-rw-r--r--value/userguide/practices.md13
11 files changed, 174 insertions, 619 deletions
diff --git a/README.md b/README.md
index 081aec02..72bcc76d 100644
--- a/README.md
+++ b/README.md
@@ -1,38 +1,37 @@
-Auto
-======
+# Auto
A collection of source code generators for [Java][java].
-Auto‽
------
+## Auto‽
-[Java][java] is full of code that is mechanical, repetitive, typically untested and sometimes the source of subtle bugs. _Sounds like a job for robots!_
+[Java][java] is full of code that is mechanical, repetitive, typically untested
+and sometimes the source of subtle bugs. _Sounds like a job for robots!_
-The Auto subprojects are a collection of code generators that automate those types of tasks. They create the code you would have written, but without the bugs.
+The Auto subprojects are a collection of code generators that automate those
+types of tasks. They create the code you would have written, but without
+the bugs.
Save time. Save code. Save sanity.
-Subprojects
------------
+## Subprojects
- * [AutoFactory](https://github.com/google/auto/tree/master/factory) - JSR-330-compatible factories
+ * [AutoFactory] - JSR-330-compatible factories
- Latest version: `0.1-beta2`
+ Latest version: `0.1-beta3`
- * [AutoService](https://github.com/google/auto/tree/master/service) - Provider-configuration files for [`ServiceLoader`](http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html)
+ * [AutoService] - Provider-configuration files for [`ServiceLoader`]
Latest version: `1.0-rc2`
- * [AutoValue](https://github.com/google/auto/tree/master/value) - Immutable [value-type](http://en.wikipedia.org/wiki/Value_object) code generation for Java 1.6+.
+ * [AutoValue] - Immutable [value-type] code generation for Java 1.6+.
- Latest version: `1.1`
+ Latest version: `1.2`
- * [Common](https://github.com/google/auto/tree/master/common) - Helper utilities for writing annotation processors.
+ * [Common] - Helper utilities for writing annotation processors.
- Latest version: `0.4`
+ Latest version: `0.6`
-License
--------
+## License
Copyright 2013 Google, Inc.
@@ -48,5 +47,11 @@ License
See the License for the specific language governing permissions and
limitations under the License.
-[java]: https://en.wikipedia.org/wiki/Java_(programming_language)
+[AutoFactory]: https://github.com/google/auto/tree/master/factory
+[AutoService]: https://github.com/google/auto/tree/master/service
+[AutoValue]: https://github.com/google/auto/tree/master/value
+[Common]: https://github.com/google/auto/tree/master/common
+[java]: https://en.wikipedia.org/wiki/Java_(programming_language)
+[value-type]: http://en.wikipedia.org/wiki/Value_object
+[`ServiceLoader`]: http://docs.oracle.com/javase/7/docs/api/java/util/ServiceLoader.html
diff --git a/value/CHANGES.md b/value/CHANGES.md
new file mode 100644
index 00000000..61d3af8f
--- /dev/null
+++ b/value/CHANGES.md
@@ -0,0 +1,59 @@
+# Auto-Value Changes
+
+## 1.1 → 1.2
+
+### Functional changes
+
+ * A **provisional** extension API has been introduced. This **will change**
+ in a later release. If you want to use it regardless, see the
+ [AutoValueExtension] class.
+
+ * Properties of primitive array type (e.g. `byte[]`) are no longer cloned
+ when read. If your @AutoValue class includes an array property, by default
+ it will get a compiler warning, which can be suppressed with
+ `@SuppressWarnings("mutable")`.
+
+ * An AutoValue.Builder type can now define both the setter and builder
+ methods like so:
+
+ ```
+ ...
+ abstract void setStrings(ImmutableList<String>);
+ abstract ImmutableList.Builder<String> stringsBuilder();
+ ...
+ ```
+ At runtime, if `stringsBuilder()...` is called then it is an error to call
+ `setStrings(...)` afterwards.
+
+ * The classes in the autovalue jar are now shaded with a `$` so they never
+ appear in IDE autocompletion.
+
+ * AutoValue now uses its own implementation of a subset of Apache Velocity,
+ so there will no longer be problems with interference between the Velocity
+ that was bundled with AutoValue and other versions that might be present.
+
+### Bugs fixed
+
+ * Explicit check for nested @AutoValue classes being private, or not being
+ static. Otherwise the compiler errors could be hard to understand,
+ especially in IDEs.
+
+ * An Eclipse bug that could occasionally lead to exceptions in the IDE has
+ been fixed (GitHub issue #200).
+
+ * Fixed a bug where AutoValue generated incorrect code if a method with a
+ type parameter was inherited by a class that supplies a concrete type for
+ that parameter. For example `StringIterator implements Iterator<String>`,
+ where the type of `next()` is String, not `T`.
+
+ * In AutoValueProcessor, fixed an exception that happened if the same abstract
+ method was inherited from more than one parent (Github Issue #267).
+
+ * AutoValue now works correctly in an environment where
+ `@javax.annotation.Generated` does not exist.
+
+ * Properties marked `@Nullable` now get `@Nullable` on the corresponding
+ constructor parameters in the generated class.
+
+[AutoValueExtension]: src/main/java/com/google/auto/value/extension/AutoValueExtension.java
+
diff --git a/value/README.md b/value/README.md
index dcb5ec17..73c959d2 100644
--- a/value/README.md
+++ b/value/README.md
@@ -1,546 +1,24 @@
# AutoValue
-*Immutable value-type code generation for Java 1.6+* <br />
+*Generated immutable value classes for Java 1.6+* <br />
***Kevin Bourrillion, Éamonn McManus*** <br />
**Google, Inc.**
-> "AutoValue may sound like a cheesy newspaper for unloading your jalopy on an
-> unsuspecting stranger, but it's actually a great tool for eliminating the
-> drudgery of writing mundane value classes in Java. It encapsulates much of the
-> advice in Effective Java Chapter 2, and frees you to concentrate on the more
-> interesting aspects of your program. The resulting program is likely to be
-> shorter, clearer, and freer of bugs. Two thumbs up."
->
-> -- *Joshua Bloch, author, Effective Java*
+**Value classes** are extremely common in Java projects. These are classes for
+which you want to treat any two instances with suitably equal field values as
+interchangeable. That's right: we're talking about those classes where you wind
+up implementing `equals`, `hashCode` and `toString` in a bloated, repetitive,
+formulaic yet error-prone fashion.
-## Contents
+Writing these methods the first time is not too bad, with the aid of a few
+helper methods and IDE templates. But once written they continue to burden
+reviewers, editors and future readers. Their wide expanses of boilerplate
+sharply decrease the signal-to-noise ratio of your code... and they love to
+harbor hard-to-spot bugs.
-<!-- generated with http://doctoc.herokuapp.com/ -->
+AutoValue provides an easier way to create immutable value classes, with a lot
+less code and less room for error, while **not restricting your freedom** to
+code almost any aspect of your class exactly the way you want it.
-- [Background](#background)
-- [Design goals](#design-goals)
-- [How to use AutoValue](#how-to-use-autovalue)
- - [In Example.java](#in-examplejava)
- - [In ExampleTest.java](#in-exampletestjava)
- - [In pom.xml](#in-pomxml)
- - [What's going on here?](#whats-going-on-here)
- - [Builders](#builders)
-- [Optional "features"](#optional-features)
- - [Data hiding](#data-hiding)
- - [Multiple creation paths](#multiple-creation-paths)
- - [Default values with builders](#default-values-with-builders)
- - [Nullability](#nullability)
- - [JavaBeans-style prefixes are optional]
- (#javabeans-style-prefixes-are-optional)
- - [Other preconditions or preprocessing]
- (#other-preconditions-or-preprocessing)
- - [Custom implementations](#custom-implementations)
- - [Nesting](#nesting)
- - [Derived fields](#derived-fields)
- - [Generics](#generics)
- - [Converting back to a builder](#converting-back-to-a-builder)
- - [Serialization](#serialization)
-- [Warnings](#warnings)
-- [Restrictions and non-features](#restrictions-and-non-features)
-- [Best practices](#best-practices)
-- [Alternatives](#alternatives)
-
-## Background
-
-Classes with value semantics are extremely common in Java. These are classes for
-which object identity is irrelevant, and instances are considered
-interchangeable based only on the equality of their field values. We will refer
-to these classes as value types in this document.
-
-To implement a value type safely and properly requires implementing `equals`,
-`hashCode` and `toString` in a bloated, repetitive, formulaic yet error-prone
-fashion. These methods are not especially time-consuming to write, especially
-with the aid of IDE templates and a few Guava helpers, but they are a continual
-burden to reviewers, editors and future readers. Their wide expanses of
-boilerplate sharply decrease the signal-to-noise ratio of your code, and
-constitute probably the single greatest violation of the DRY (Don't Repeat
-Yourself) principle we are ever forced to commit.
-
-AutoValue provides an easier way to create immutable value types, with less code
-and less room for error, while **not restricting your freedom** to code any
-aspect of your class just the way you want it.
-
-## Design goals
-
-AutoValue is the only solution to the value types problem in Java (that we are
-aware of) having all of the following characteristics:
-
-* Usage is **API-invisible** (callers cannot become dependent on your choice
- to use it, or generally even tell the difference)
-* No required runtime dependencies
-* No performance penalty vs. hand-written code.
-* Virtually no limitations on what you can do with your class (private
- accessors, implementing interfaces, custom `hashCode()`, etc. See the
- "optional features" section.)
-* Minimal extralinguistic magic
-
-## How to use AutoValue
-
-The way to use AutoValue is a little surprising at first! Create your value type
-as an abstract class, containing an abstract accessor method for each desired
-field. This accessor can be any non-void, parameterless method. Add the
-@AutoValue annotation to your class, and AutoValue will automatically generate
-an implementing class.
-
-### In `Example.java`
-
-```java
-import com.google.auto.value.AutoValue;
-
-class Example {
-  @AutoValue
-  abstract static class Animal {
-    static Animal create(String name, int numberOfLegs) {
-      return new AutoValue_Example_Animal(name, numberOfLegs);
- // (or just AutoValue_Animal if this is not nested)
-    }
-
-    abstract String name();
-    abstract int numberOfLegs();
-  }
-}
-```
-
-That's it! (In real life, some classes and methods would presumably be public
-and have Javadoc.)
-
-The central idea behind AutoValue is: if you can create an abstract class that
-has one "obvious" reasonable implementation, a tool ought to be able to write
-that implementation for you. And now it does.
-
-### In `ExampleTest.java`
-
-To a consumer, this looks and functions like any other object. The simple test
-below illustrates that behavior. Note that in real life, you would write tests
-that actually **do something interesting** with the object, instead of just
-checking field values going in and out.
-
-```java
-public void testAnimal() {
- Animal dog = Animal.create("dog", 4);
- assertEquals("dog", dog.name());
- assertEquals(4, dog.numberOfLegs());
-
- // You really don't need to write tests like these; just illustrating.
-
- assertTrue(Animal.create("dog", 4).equals(dog));
- assertFalse(Animal.create("cat", 4).equals(dog));
- assertFalse(Animal.create("dog", 2).equals(dog));
-
- assertEquals("Animal{name=dog, numberOfLegs=4}", dog.toString());
-}
-```
-
-
-### In `pom.xml`
-
-For Maven users, add the following to your Maven configuration:
-
-```xml
-<dependency>
- <groupId>com.google.auto.value</groupId>
- <artifactId>auto-value</artifactId>
- <version>1.1</version>
- <scope>provided</scope>
-</dependency>
-```
-
-### What's going on here?
-
-AutoValue runs as a standard annotation processor in javac. It generates source
-code, in your package, for a *package-private* implementation class called
-**`AutoValue_Example_Animal`**. The generated class contains a field for each
-abstract accessor method, and the generated constructor sets these fields. It
-implements the accessor methods to simply return those references/values. It
-implements equals to compare these values in the standard fashion, and
-implements an appropriate corresponding `hashCode`. It implements `toString` to
-return an unspecified string representation of the class.
-
-Consumers of your value type don't need to know any of this. They just invoke
-your provided factory method and get a well-behaved instance back.
-
-### Builders
-
-*(since 1.1)*
-
-You may prefer to construct some objects through _builders_. If there is a
-nested interface or abstract class that is annotated with `@AutoValue.Builder`,
-then AutoValue will implement it to make it a builder class. The
-`@AutoValue.Builder` interface or class is conventionally called `Builder`. It
-must have method for every property to set the value of the property, and a
-build method. Here is the example above written using builders.
-
-```java
-import com.google.auto.value.AutoValue;
-
-class Example {
-  @AutoValue
-  abstract static class Animal {
- static Builder builder() {
- return new AutoValue_Example_Animal.Builder();
- }
-
-    abstract String name();
-    abstract int numberOfLegs();
-
- @AutoValue.Builder
- abstract static class Builder {
- abstract Builder name(String s);
- abstract Builder numberOfLegs(int n);
- abstract Animal build();
- }
-  }
-}
-```
-
-Now client code can look something like this:
-
-```java
-Animal dog = Animal.builder().name("dog").numberOfLegs(4).build();
-```
-
-## Optional "features"
-
-Many of the following are not even features of AutoValue itself, just features
-of the Java language which (unlike some other solutions to the value types
-problem) AutoValue doesn't get in the way of.
-
-### Data hiding
-
-Your accessors don't have to be public! They do have to be at least
-package-private. The fields themselves cannot be directly accessed.
-
-### Multiple creation paths
-
-You can offer as many static creation methods as you need, named descriptively,
-to cover different combinations of parameters. They do not need to be named
-`create` as in the example.
-
-### Default values with builders
-
-Generated builders require every property to be set, except `@Nullable`
-properties. If you want to define a default value for a property, set it in the
-`builder()` method before returning. Here's how to define that animals have 4
-legs by default:
-
-```java
-class Example {
-  @AutoValue
-  abstract static class Animal {
- static Builder builder() {
- return new AutoValue_Example_Animal.Builder()
- .numberOfLegs(4);
- }
- // ...remainder as before...
-  }
-}
-```
-
-### Nullability
-
-By default, AutoValue inserts a not-null check for each non-primitive parameter
-passed to the generated constructor. If your class has a property that is
-allowed to be null, apply `@Nullable` to the corresponding accessor method and
-factory parameter. This has two effects: AutoValue will skip the null check, and
-generate null-friendly code for `equals` and `hashCode`. The `@Nullable`
-annotation can be `javax.annotation.Nullable` or a `Nullable` annotation defined
-in any other package.
-
-### JavaBeans-style prefixes are optional
-
-In the example above, we used the `name()` and `numberOfLegs()` methods to
-define the properties of the object. If you prefer, you can use JavaBeans-style
-method names, like `getName()` and `getNumberOfLegs()` to achieve the same
-effect. The property names will still be `name` and `numberOfLegs`, for example
-in the result of `toString()`. This applies only if every abstract method looks
-like `getX()` or `boolean isX()` for some non-empty string X.
-
-Similarly, in a builder you can use methods like `name(String s)` and
-`numberOfLegs(int n)` or methods like `setName(String s)` and
-`setNumberOfLegs(int n)`. Again, every abstract method must follow the same one
-of the two conventions.
-
-### Other preconditions or preprocessing
-
-If you need to check preconditions or perform any other preparatory steps,
-insert the code to do so into your static factory method before invoking the
-generated constructor. Remember that null checks are already present in the
-generated constructor.
-
-When using builders, you can validate by implementing your own build() method
-that calls the generated build method, conventionally called autoBuild(). You
-can construct an object provisionally and inspect its properties before
-returning it. Here's how our example might be validated:
-
-```java
-class Example {
-  @AutoValue
-  abstract static class Animal {
- ...
- @AutoValue.Builder
- abstract static class Builder {
- abstract Builder name(String s);
- abstract Builder numberOfLegs(int n);
-
- abstract Animal autoBuild();
- Animal build() {
- Animal animal = autoBuild();
- if (animal.numberOfLegs() < 0) {
- throw new IllegalStateException("Negative legs");
- }
- return animal;
- }
- }
-  }
-}
-```
-
-If the Builder class is public, typically `build()` will be too but
-`autoBuild()` will be package-private.
-
-Sometimes it may be more convenient to consult the value in the builder before
-calling `autoBuild()`. If the `Builder` class has an abstract method with the
-same name and type as one of the methods in the `@AutoValue` class, it will be
-implemented to return the value set on the builder, or throw an exception if no
-value has been set. Like `autoBuild()`, these getter methods will typically not
-be public.
-
-```java
-class Example {
-  @AutoValue
-  abstract static class Animal {
- abstract String name();
- abstract int numberOfLegs();
-
- ...
-
- @AutoValue.Builder
- abstract static class Builder {
- abstract Builder name(String s);
- abstract Builder numberOfLegs(int n);
- abstract int numberOfLegs();
-
- abstract Animal autoBuild();
- Animal build() {
- if (numberOfLegs() < 0) {
- throw new IllegalStateException("Negative legs");
- }
- return autoBuild();
- }
- }
-  }
-}
-```
-
-### Custom implementations
-
-Don't like the `equals`, `hashCode` or `toString` method AutoValue generates?
-You can underride it! Just write your own, directly in your abstract class;
-AutoValue will see this and skip generating its own.
-
-### Nesting
-
-Your hand-written abstract value type can be nested at any level. The generated
-implementation class is named `AutoValue_` plus each component of the class
-named separated by underscores. For example, for the abstract class
-`Foo.Bar.Qux`, the generated implementation class is `AutoValue_Foo_Bar_Qux`, in
-the same package.
-
-### Derived fields
-
-If a field exists to cache a derived value, and should be ignored in `equals`,
-`hashCode` and `toString`, define it directly in your class instead of providing
-an abstract accessor for it. AutoValue will know nothing of it.
-
-You may have fields you wish to ignore in equals for other reasons. We're sorry:
-AutoValue doesn't work for these cases, since there's no way to pass the extra
-parameter "through" the generated class constructor.
-
-### Generics
-
-An `@AutoValue` class can have type parameters, as illustrated in these
-examples:
-
-```java
-@AutoValue
-abstract class MapEntry<K extends Comparable<K>, V> implements Map.Entry<K, V> {
- static <K extends Comparable<K>, V> MapEntry<K, V> create(K key, V value) {
- return new AutoValue_MapEntry<K, V>(key, value);
- }
- ...
-}
-```
-
-or
-
-```java
-@AutoValue
-abstract class MapEntry<K extends Comparable<K>, V> implements Map.Entry<K, V> {
- static <K extends Comparable<K>, V> Builder<K, V> builder() {
- return new AutoValue_MapEntry.Builder<K, V>();
- }
-
- abstract static class Builder<K extends Comparable<K>, V> {
- abstract Builder setKey(K key);
- abstract Builder setValue(V value);
- abstract MapEntry<K, V> build();
- }
- ...
-}
-```
-
-### Converting back to a builder
-
-An `@AutoValue` class with a builder can optionally have an abstract method that
-returns the builder type. It will be implemented by initializing the builder
-with the values of the properties. This can be exposed directly to clients, or
-used to implement "wither" methods that return a new object that is the same as
-the original one except for one changed property. Here is an example:
-
-```java
-class Example {
-  @AutoValue
-  abstract static class Animal {
- static Builder builder() {
- return AutoValue_Example_Animal.Builder();
- }
-
- abstract Builder toBuilder();
-
- Animal withNumberOfLegs(int n) {
- return toBuilder().numberOfLegs(n).build();
- }
- // ...remainder as before...
-  }
-}
-```
-
-### Serialization
-
-The generated class will be serializable if your abstract class implements
-`Serializable`. It will be GWT-serializable if your abstract class is annotated
-with `@GwtCompatible(serializable = true)` (any annotation with that name and
-field will do, such as the one included in [Guava]).
-
-(Ordinarily, abstract types should not be serializable, but in this case it's
-harmless, since we truly expect no other implementations to ever exist.)
-
-There is no way to mark individual fields as transient or customize the
-serialization behavior.
-
-[Guava]: https://github.com/google/guava
-
-## Warnings
-
-Use of AutoValue has one serious **negative consequence**: certain formerly safe
-refactorings could now break your code, and be caught only by your tests.
-
-If you are not using builders, you must ensure that parameters are passed to the
-auto-generated constructor in the ***same order*** the corresponding accessor
-methods are defined in the file. **Your tests must be sufficient** to catch any
-field ordering problem. In most cases this should be the natural outcome from
-testing whatever actual purpose this value type was created for! In other cases
-a very simple test like the one shown above is enough.
-
-We reserve the right to **change the `hashCode` implementation** at any time. Do
-not depend on the order your objects appear in hash maps (use `ImmutableMap` or
-`LinkedHashMap`!), and never persist these hash codes.
-
-
-## Restrictions and non-features
-
-* Using AutoValue limits your public creation API to static factory methods,
- not constructors. See *Effective Java* Item 1 for several reasons this is
- usually a good idea anyway.
-
-* AutoValue does not and will not support creating *mutable* value types. (We
- may consider adding support for `withField`-style methods, which return a
- new immutable copy of the original instance with one field value changed.)
-
-* One `@AutoValue` class may not extend another. As explained in *Effective
- Java*, inheritance of value types simply doesn't work.
-
-* Object arrays are not and will not be supported, including multidimensional
- primitive array types. Use a `Collection` type instead, such as
- `ImmutableList`.
-
-* Your accessor methods may not be `private` -- but they may be
- package-private. The same is true for your `@AutoValue` class itself.
-
-* We don't generate `compareTo`, because we feel you need the expressiveness
- that [`ComparisonChain`] provides, and we can't beat it at its own game. If
- we find later that a large minority of AutoValue classes are implementing
- compareTo by the exact same formula, we will reconsider this feature.
-
-* AutoValue currently doesn't inspect the `new AutoValue_Foo` line to issue
- warnings on parameter order. (There are certain technical issues with doing
- so.) As stated above in Warnings, you had better have some test somewhere
- that will catch such problems. Or you can use builders to avoid having a
- parameter order at all.
-
-* It might seem convenient to use AutoValue to implement annotation
- interfaces, which frameworks such as [Guice] occasionally require. But in
- fact such interfaces must obey the contracts for `equals` and `hashCode`
- specified by java.lang.annotation.Annotation, and the implementations of
- those methods that AutoValue would generate do not. Instead, the
- com.google.auto.value package includes another annotation `@AutoAnnotation`
- specifically for this case. See its documentation for more details.
-
-[`ComparisonChain`]: http://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/ComparisonChain.html
-[Guice]: https://github.com/google/guice/wiki/BindingAnnotations#user-content-binding-annotations-with-attributes
-
-## Best practices
-
-You should add a **package-private constructor** to your abstract class,
-although we have omitted it for brevity in our examples. This accomplishes two
-things: it prevents an undocumented public constructor (that no one can even
-call) from appearing in your javadoc, and it prevents users outside your package
-from creating their own subclasses (and potentially subverting your
-immutability).
-
-In fact, **you should virtually never need an alternative implementation of your
-hand-written abstract class**, whether hand-written or generated by a mocking
-framework. Your class can and should contain simple intrinsic behavior, but if
-that behavior has enough complexity or enough dependencies that it actually
-needs to be mocked or faked, split it into a separate type that is *not* a value
-type. Otherwise it permits an instance with "real" behavior and one with
-"mock/fake" behavior to be `equals`, which does not make sense. Keep your value
-types straightforward.
-
-Other code in the same package will be able to directly access the generated
-class, *but should not*. It's best if each generated class has **one and only
-one reference** from your source code. If you have multiple creation methods,
-have them all call through to the same point, so there is still one call to the
-generated file, and one place to insert preconditions, etc.
-
-**Avoid mutable field types**, such as arrays, especially if you make your
-accessor methods `public`. The generated accessors won't copy the field value on
-its way out, so you'd be exposing your internal state. This doesn't mean your
-factory method can't *accept* mutable types as input parameters. Example:
-
-```java
-@AutoValue
-public abstract class ListExample {
- abstract ImmutableList<String> names();
-
- public static ListExample create(List<String> mutableNames) {
- return new AutoValue_ListExample(ImmutableList.copyOf(mutableNames));
- }
-}
-```
-
-Finally, if you choose to provide an explicit `equals`, `hashCode` or `toString`
-implementation, please make it **`final`**, so readers don't have to wonder
-whether AutoValue is overriding it.
-
-## Alternatives
-
-This [slide presentation] walks through several competing solutions to this
-problem and shows why we considered them insufficient.
-
-[slide presentation]: https://docs.google.com/presentation/d/14u_h-lMn7f1rXE1nDiLX0azS3IkgjGl5uxp5jGJ75RE/edit
+For more information, consult the [detailed documentation]
+(userguide/index.md)
diff --git a/value/src/it/functional/pom.xml b/value/src/it/functional/pom.xml
index f0ee5544..a036374f 100644
--- a/value/src/it/functional/pom.xml
+++ b/value/src/it/functional/pom.xml
@@ -63,7 +63,10 @@
<build>
<plugins>
<plugin>
- <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.5</version>
+ </plugin>
+ <plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
diff --git a/value/src/test/java/com/google/auto/value/processor/GuavaCollectionBuildersTest.java b/value/src/test/java/com/google/auto/value/processor/GuavaCollectionBuildersTest.java
index 7bf77957..8df113e0 100644
--- a/value/src/test/java/com/google/auto/value/processor/GuavaCollectionBuildersTest.java
+++ b/value/src/test/java/com/google/auto/value/processor/GuavaCollectionBuildersTest.java
@@ -34,7 +34,7 @@ import java.util.Arrays;
@RunWith(JUnit4.class)
public class GuavaCollectionBuildersTest {
private static final ImmutableSet<String> NON_BUILDABLE_COLLECTIONS =
- ImmutableSet.of("ImmutableCollection", "ImmutableMapBuilder");
+ ImmutableSet.of("ImmutableCollection");
@Rule public final Expect expect = Expect.create();
diff --git a/value/userguide/builders-howto.md b/value/userguide/builders-howto.md
index 76a5eadc..847e5177 100644
--- a/value/userguide/builders-howto.md
+++ b/value/userguide/builders-howto.md
@@ -30,7 +30,7 @@ How do I...
* ... [offer **both** accumulation and set-at-once methods for the same
collection-valued property?](#collection_both)
-## ... use (or not use) `set` prefixes? {#beans}
+## <a name="beans"></a>... use (or not use) `set` prefixes?
Just as you can choose to use JavaBeans-style names for property getters
(`getFoo()` instead of plain `foo()`) in your value class, you can use them for
@@ -62,13 +62,13 @@ abstract class Animal {
}
```
-## ... use different names besides `builder()`/`Builder`/`build()`? {#build_names}
+## <a name="build_names"></a>... use different names besides `builder()`/`Builder`/`build()`?
Use whichever names you like; AutoValue doesn't actually care.
(We would gently recommend these names as conventional.)
-## ... specify a default value for a property? {#default}
+## <a name="default"></a>... specify a default value for a property?
What should happen when a caller does not supply a value for a property before
calling `build()`? If the property in question is [nullable](howto.md#nullable),
@@ -105,7 +105,7 @@ abstract class Animal {
}
```
-## ... initialize a builder to the same property values as an existing value instance {#to_builder}
+## <a name="to_builder"></a>... initialize a builder to the same property values as an existing value instance
Suppose your caller has an existing instance of your value class, and wants to
change only one or two of its properties. Of course, it's immutable, but it
@@ -120,7 +120,7 @@ your abstract builder type, to your value class. AutoValue will implement it.
public abstract Builder toBuilder();
```
-## ... include `with-` methods on my value class for creating slightly altered instances? {#withers}
+## <a name="withers"></a>... include `with-` methods on my value class for creating slightly altered instances?
This is a somewhat common pattern among immutable classes. You can't have
setters, but you can have methods that act similarly to setters by returning a
@@ -156,7 +156,7 @@ public abstract class Animal {
Note that it's your free choice what to make public (`toBuilder`, `withName`,
neither, or both).
-## ... validate property values? {#validate}
+## <a name="validate"></a>... validate property values?
Validating properties is a little less straightforward than it is in the
[non-builder case](howto.md#validate).
@@ -196,7 +196,7 @@ public abstract class Animal {
}
```
-## ... normalize (modify) a property value at `build` time? {#normalize}
+## <a name="normalize"></a>... normalize (modify) a property value at `build` time?
Suppose you want to convert the animal's name to lower case.
@@ -237,14 +237,14 @@ been set on the `Builder`. If no value has been set for a non-[nullable]
Getters should generally only be used within the `Builder` as shown, so they are
not public.
-## ... expose *both* a builder *and* a factory method? {#both}
+## <a name="both"></a>... expose *both* a builder *and* a factory method?
If you use the builder option, AutoValue will not generate a visible constructor
for the generated concrete value class. If it's important to offer your caller
the choice of a factory method as well as the builder, then your factory method
implementation will have to invoke the builder itself.
-## ... use a collection-valued property? {#collection}
+## <a name="collection"></a>... use a collection-valued property?
Value objects should be immutable, so if a property of one is a collection then
that collection should be immutable too. We recommend using Guava's [immutable
@@ -290,7 +290,7 @@ public abstract class Animal {
[immutable collections]: https://github.com/google/guava/wiki/ImmutableCollectionsExplained
-### ... let my builder *accumulate* values for a collection-valued property (not require them all at once)? {#accumulate}
+### <a name="accumulate"></a>... let my builder *accumulate* values for a collection-valued property (not require them all at once)?
Instead of defining a setter for an immutable collection `foos`, you can define
a method `foosBuilder()` that returns the associated builder type for that
@@ -347,7 +347,7 @@ Instead they are forced to hold the builder itself in a temporary variable:
One solution for this problem is just below.
-### ... accumulate values for a collection-valued property, without "breaking the chain"? {#add}
+### <a name="add"></a>... accumulate values for a collection-valued property, without "breaking the chain"?
Another option is to keep `countriesBuilder()` itself non-public, only use it to
implement a public `addCountry` method:
diff --git a/value/userguide/builders.md b/value/userguide/builders.md
index a11e799d..37f137da 100644
--- a/value/userguide/builders.md
+++ b/value/userguide/builders.md
@@ -9,16 +9,15 @@ Fortunately, AutoValue can generate builder classes too! This page explains how.
Note that we recommend reading and understanding the basic usage shown in the
[introduction](index.md) first.
-<!-- TODO: table of contents that works both internal/external -->
-## How to use AutoValue with Builders {#howto}
+## How to use AutoValue with Builders<a name="howto"></a>
As explained in the introduction, the AutoValue concept is that **you write an
abstract value class, and AutoValue implements it**. Builder generation works in
the exact same way: you also create an abstract builder class, nesting it inside
your abstract value class, and AutoValue generates implementations for both.
-### In `Animal.java` {#example_java}
+### In `Animal.java`<a name="example_java"></a>
```java
import com.google.auto.value.AutoValue;
@@ -45,7 +44,7 @@ Note that in real life, some classes and methods would presumably be public and
have **Javadoc**. We're leaving these off in the User Guide only to keep the
examples clean and short.
-### Usage {#usage}
+### Usage<a name="usage"></a>
```java
public void testAnimal() {
@@ -62,19 +61,19 @@ public void testAnimal() {
}
```
-### What does AutoValue generate? {#generated}
+### What does AutoValue generate?<a name="generated"></a>
For the `Animal` example shown above, here is [typical code AutoValue might
generate](generated-builder-example.md).
-## Warnings {#warnings}
+## Warnings<a name="warnings"></a>
Be sure to put the static `builder()` method directly in your value class (e.g.,
`Animal`) and not the nested abstract `Builder` class. That ensures that the
`Animal` class is always initialized before `Builder`. Otherwise you may be
exposing yourself to initialization-order problems.
-## How do I... {#howto}
+## <a name="howto"></a>How do I...
* ... [use (or not use) `set` **prefixes**?](builders-howto.md#beans)
* ... [use different **names** besides `builder()`/`Builder`/`build()`?]
diff --git a/value/userguide/howto.md b/value/userguide/howto.md
index e0777d55..574d0aea 100644
--- a/value/userguide/howto.md
+++ b/value/userguide/howto.md
@@ -36,11 +36,11 @@ How do I...
API?](#public_constructor)
* ... [use AutoValue on an **interface**, not abstract class?](#interface)
-## ... also generate a builder for my value class? {#builder}
+## <a name="builder"></a>... also generate a builder for my value class?
Please see [AutoValue with builders](builders.md).
-## ... use AutoValue with a nested class? {#nested}
+## <a name="nested"></a>... use AutoValue with a nested class?
AutoValue composes the generated class name in the form
`AutoValue_`*`Outer_Middle_Inner`*.
@@ -58,7 +58,7 @@ class Outer {
...
```
-## ... use (or not use) JavaBeans-style name prefixes? {#beans}
+## <a name="beans"></a>... use (or not use) JavaBeans-style name prefixes?
Some developers prefer to name their accessors with a `get-` or `is-` prefix,
but would prefer that only the "bare" property name be used in `toString` and
@@ -74,7 +74,7 @@ Note that, in keeping with the JavaBeans specification, the `is-` prefix is only
allowed on `boolean`-returning methods. `get-` is allowed on any type of
accessor.
-## ... use nullable properties? {#nullable}
+## <a name="nullable"></a>... use nullable properties?
Ordinarily the generated constructor will reject any null values. If you want to
accept null, simply apply any annotation named `@Nullable` to the appropriate
@@ -96,7 +96,7 @@ This example also shows annotating the corresponding `create` parameter with
`@Nullable`. AutoValue does not actually require this annotation, only the one
on the accessor, but we recommended it as useful documentation to your caller.
-## ... perform other validation? {#validate}
+## <a name="validate"></a>... perform other validation?
Null checks are added automatically (as [above](#nullable)). For other types of
precondition checks or pre-processing, just add them to your factory method:
@@ -108,7 +108,7 @@ static MyType create(String first, String second) {
}
```
-## ... use a property of a mutable type? {#mutable_property}
+## <a name="mutable_property"></a>... use a property of a mutable type?
First, check if the mutable type has a corresponding immutable cousin. For
example, the types `List<String>` and `String[]` have the immutable counterpart
@@ -152,7 +152,7 @@ public abstract class MutableExample {
Note: this is a perfectly ugly workaround, not a sensible practice!
-## ... use a custom implementation of `equals`, etc.? {#custom}
+## <a name="custom"></a>... use a custom implementation of `equals`, etc.?
Simply write your custom implementation; AutoValue will notice this and will
skip generating its own. Your hand-written logic will thus be inherited on the
@@ -184,12 +184,12 @@ class PleaseOverrideExample extends SuperclassThatDefinesToString {
<!-- TODO(kevinb): should the latter part have been split out? -->
-## ... have multiple `create` methods, or name it/them differently? {#create}
+## <a name="create"></a>... have multiple `create` methods, or name it/them differently?
Just do it! AutoValue doesn't actually care. This [best practice item]
(practices.md#one_reference) may be relevant.
-## ... ignore certain properties in `equals`, etc.? {#ignore}
+## <a name="ignore"></a>... ignore certain properties in `equals`, etc.?
Suppose your value class has an extra field that shouldn't be included in
`equals` or `hashCode` computations. One common reason is that it is a "cached"
@@ -242,31 +242,31 @@ abstract class IgnoreExample {
Note that in both cases the field ignored for `equals` and `hashCode` is also
ignored by `toString`; to AutoValue it simply doesn't exist.
-## ... have AutoValue also implement abstract methods from my supertypes? {#supertypes}
+## <a name="supertypes"></a>... have AutoValue also implement abstract methods from my supertypes?
AutoValue will recognize every abstract accessor method whether it is defined
directly in your own hand-written class or in a supertype.
<!-- TODO(kevinb): what about the order? -->
-## ... use AutoValue with a generic class? {#generic}
+## <a name="generic"></a>... use AutoValue with a generic class?
There's nothing to it: just add type parameters to your class and to your call
to the generated constructor.
-## ... make my class Java- or GWT-serializable? {#serialize}
+## <a name="serialize"></a>... make my class Java- or GWT-serializable?
Just add `implements Serializable` or the `@GwtCompatible(serializable = true)`
annotation (respectively) to your hand-written class; it (as well as any
`serialVersionUID`) will be duplicated on the generated class, and you'll be
good to go.
-## ... apply an annotation to a generated field? {#annotate_field}
+## <a name="annotate_field"></a>... apply an annotation to a generated field?
Your only option is to put the same annotation on your hand-written abstract
accessor method, if possible.
-## ... use AutoValue to implement an annotation type? {#annotation}
+## <a name="annotation"></a>... use AutoValue to implement an annotation type?
Most users should never have the need to programmatically create "fake"
annotation instances. But if you do, using `@AutoValue` in the usual way will
@@ -294,7 +294,7 @@ public class Names {
For more details, see the [`AutoAnnotation` javadoc]
(http://github.com/google/auto/blob/master/value/src/main/java/com/google/auto/value/AutoAnnotation.java#L24).
-## ... also include setter (mutator) methods? {#setters}
+## <a name="setters"></a>... also include setter (mutator) methods?
You can't; AutoValue only generates immutable value classes.
@@ -303,7 +303,7 @@ questionable practice in the first place. Equal instances of a value class are
treated as *interchangeable*, but they can't truly be interchangeable if one
might be mutated and the other not.
-## ... also generate `compareTo`? {#compareTo}
+## <a name="compareTo"></a>... also generate `compareTo`?
AutoValue intentionally does not provide this feature. It is better for you to
roll your own comparison logic using the new methods added to [`Comparator`]
@@ -316,14 +316,14 @@ Since these mechanisms are easy to use, require very little code, and give you
the flexibility you need, there's really no way for AutoValue to improve on
them!
-## ... use a primitive array for a property value? {#primitive_array}
+## <a name="primitive_array"></a>... use a primitive array for a property value?
Go right ahead! AutoValue will generate code that acts on the *values* stored
the array, not the object identity of the array itself, which is (with virtual
certainty) what you want. Heed the warnings given above about [mutable
properties](#mutable_property).
-## ... use an object array for a property value? {#object_array}
+## <a name="object_array"></a>... use an object array for a property value?
This is not allowed. Object arrays are very badly-behaved and unlike primitive
arrays, they can be replaced with a proper `List` implementation for very little
@@ -333,24 +333,24 @@ added cost.
If it's important to accept an object array at construction time, refer to the
*first* example shown [here](#mutable_property).
-## ... have one `@AutoValue` class extend another? {#inherit}
+## <a name="inherit"></a>... have one `@AutoValue` class extend another?
This ability is intentionally not supported, because there is no way to do it
correctly. See *Effective Java, 2nd Edition* Item 8.
-## ... keep my accessor methods private? {#private_accessors}
+## <a name="private_accessors"></a>... keep my accessor methods private?
We're sorry. This is one of the rare and unfortunate restrictions AutoValue's
approach places on your API. Your accessor methods don't have to be *public*,
but they must be at least package-visible.
-## ... expose a constructor, not factory method, as my public creation API? {#public_constructor}
+## <a name="public_constructor"></a>... expose a constructor, not factory method, as my public creation API?
We're sorry. This is one of the rare restrictions AutoValue's approach places on
your API. However, note that static factory methods are recommended over public
constructors by *Effective Java*, Item 1.
-## ... use AutoValue on an interface, not abstract class? {#interface}
+## <a name="interface"></a>... use AutoValue on an interface, not abstract class?
Interfaces are not allowed. The only advantage of interfaces we're aware of is
that you can omit `public abstract` from the methods. That's not much. On the
diff --git a/value/userguide/index.md b/value/userguide/index.md
index 1f08d280..e76a72cb 100644
--- a/value/userguide/index.md
+++ b/value/userguide/index.md
@@ -12,9 +12,8 @@
>
> -- *Joshua Bloch, author, Effective Java*
-<!-- TODO: table of contents that works both internal/external -->
-## Background {#background}
+## <a name="background"></a>Background
**Value classes** are extremely common in Java projects. These are classes for
which you want to treat any two instances with suitably equal field values as
@@ -35,7 +34,7 @@ code almost any aspect of your class exactly the way you want it.
This page will walk you through how to use AutoValue. Looking for a little more
persuasion? Please see [Why AutoValue?](why.md).
-## How to use AutoValue {#howto}
+## <a name="howto"></a>How to use AutoValue
The AutoValue concept is extremely simple: **You write an abstract class, and
AutoValue implements it.** That is all there is to it; there is literally *no*
@@ -45,7 +44,7 @@ configuration.
builder class. If you're more interested in the builder support, continue
reading at [AutoValue with Builders](builders.md) instead.
-### In your value class {#example_java}
+### <a name="example_java"></a>In your value class
Create your value class as an *abstract* class, with an abstract accessor method
for each desired property, and bearing the `@AutoValue` annotation.
@@ -69,20 +68,33 @@ Note that in real life, some classes and methods would presumably be public and
have Javadoc. We're leaving these off in the User Guide only to keep the
examples short and simple.
-### In `pom.xml` {#example_pom}
+### In `pom.xml`
-Maven users, add the following to your configuration:
+Maven users should add the following to the project's `pom.xml` file:
```xml
<dependency>
<groupId>com.google.auto.value</groupId>
<artifactId>auto-value</artifactId>
- <version>1.1</version>
+ <version>1.2</version>
<scope>provided</scope>
</dependency>
```
-### Usage {#usage}
+Gradle users should install the annotation processing plugin [as described in
+these instructions][tbroyer-apt] and then use it in the `build.gradle` script:
+
+```groovy
+dependencies {
+ compileOnly "com.google.auto.value:auto-value:1.2"
+ apt "com.google.auto.value:auto-value:1.2"
+}
+```
+
+[tbroyer-apt]: https://plugins.gradle.org/plugin/net.ltgt.apt
+
+
+### <a name="usage"></a>Usage
Your choice to use AutoValue is essentially *API-invisible*. That means that to
the consumer of your class, your class looks and functions like any other. The
@@ -105,7 +117,7 @@ public void testAnimal() {
}
```
-### What's going on here? {#whats_going_on}
+### <a name="whats_going_on"></a>What's going on here?
AutoValue runs inside `javac` as a standard annotation processor. It reads your
abstract class and infers what the implementation class should look like. It
@@ -131,7 +143,7 @@ generate](generated-example.md).
Note that *consumers* of your value class *don't need to know any of this*. They
just invoke your provided factory method and get a well-behaved instance back.
-## Warnings {#warnings}
+## <a name="warnings"></a>Warnings
Be careful that you don't accidentally pass parameters to the generated
constructor in the wrong order. You must ensure that **your tests are
@@ -146,11 +158,11 @@ Never persist the result of `hashCode` or use it for any other unintended
purpose, and be careful never to depend on the order your values appear in
unordered collections like `HashSet`.
-## Why should I use AutoValue? {#why}
+## <a name="why"></a>Why should I use AutoValue?
See [Why AutoValue?](why.md).
-## How do I... {#more_howto}
+## <a name="more_howto"></a>How do I...
How do I...
@@ -186,7 +198,7 @@ How do I...
<!-- TODO(kevinb): should the above be only a selected subset? -->
-## More information {#more}
+## <a name="more"></a>More information
See the links in the sidebar at the top left.
diff --git a/value/userguide/performance.md b/value/userguide/performance.md
index 1ad6c3b9..36d4315e 100644
--- a/value/userguide/performance.md
+++ b/value/userguide/performance.md
@@ -1,6 +1,6 @@
# Performance notes
-TODO(kevinb): write a real page
+TODO: write a real page
* should perform like a hand-written class after HotSpot compiles it
(generated accessors can be inlined)
diff --git a/value/userguide/practices.md b/value/userguide/practices.md
index c0c79b76..9e7320b6 100644
--- a/value/userguide/practices.md
+++ b/value/userguide/practices.md
@@ -1,14 +1,13 @@
# Best practices
-[TOC]
-## "Equals means interchangeable" {#interchangeable}
+## <a name="interchangeable"></a>"Equals means interchangeable"
Don't use AutoValue to implement value semantics unless you really want value
semantics. In particular, you should never care about the difference between two
equal instances.
-## Avoid mutable property types {#mutable_properties}
+## <a name="mutable_properties"></a>Avoid mutable property types
Avoid mutable types, including arrays, for your properties, especially if you
make your accessor methods `public`. The generated accessors don't copy the
@@ -28,7 +27,7 @@ public abstract class ListExample {
}
```
-## Keep behavior simple and dependency-free {#simple}
+## <a name="simple"></a>Keep behavior simple and dependency-free
Your class can (and should) contain *simple* intrinsic behavior. But it
shouldn't require complex dependencies and shouldn't access static state.
@@ -40,7 +39,7 @@ actually needs to be mocked or faked, split it into a separate type that is
*not* a value type. Otherwise it permits an instance with "real" behavior and
one with "mock/fake" behavior to be `equals`, which does not make sense.
-## One reference only {#one_reference}
+## <a name="one_reference"></a>One reference only
Other code in the same package will be able to directly access the generated
class, but *should not*. It's best if each generated class has one and only one
@@ -50,7 +49,7 @@ delegate to the same hand-written method, so there is still only one point of
contact with the generated code. This way, you have only one place to insert
precondition checks or other pre- or postprocessing.
-## Mark all concrete methods `final` {#final}
+## <a name="final"></a>Mark all concrete methods `final`
Consider that other developers will try to read and understand your value class
while looking only at your hand-written class, not the actual (generated)
@@ -59,7 +58,7 @@ to wonder whether the generated subclass might be overriding them. This is
especially helpful if you are *[underriding](howto.md#custom)* `equals`,
`hashCode` or `toString`!
-## Maybe add an explicit, inaccessible constructor {#constructor}
+## <a name="constructor"></a>Maybe add an explicit, inaccessible constructor
There are a few small advantages to adding a package-private, parameterless
constructor to your abstract class. It prevents unwanted subclasses, and