1 /* 2 * Copyright 2018 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.google.auto.value; 17 18 import java.lang.annotation.ElementType; 19 import java.lang.annotation.Retention; 20 import java.lang.annotation.RetentionPolicy; 21 import java.lang.annotation.Target; 22 23 /** 24 * Specifies that the annotated class is a <em>one-of</em> class, also known as a <a 25 * href="https://en.wikipedia.org/wiki/Tagged_union"><em>tagged union</em></a>. An 26 * {@code @AutoOneOf} class is very similar to an {@link AutoValue @AutoValue} class, in that its 27 * abstract methods define a set of properties. But unlike {@code @AutoValue}, only one of those 28 * properties is defined in any given instance. 29 * 30 * <pre>{@code @AutoOneOf(StringOrInteger.Kind.class) 31 * public abstract class StringOrInteger { 32 * public enum Kind {STRING, INTEGER} 33 * 34 * public abstract Kind getKind(); 35 * 36 * public abstract String string(); 37 * public abstract int integer(); 38 * 39 * public static StringOrInteger ofString(String s) { 40 * return AutoOneOf_StringOrInteger.string(s); 41 * } 42 * 43 * public static StringOrInteger ofInteger(int i) { 44 * return AutoOneOf_StringOrInteger.integer(i); 45 * } 46 * } 47 * 48 * String client(StringOrInteger stringOrInteger) { 49 * switch (stringOrInteger.getKind()) { 50 * case STRING: 51 * return "the string '" + stringOrInteger.string() + "'"; 52 * case INTEGER: 53 * return "the integer " + stringOrInteger.integer(); 54 * } 55 * throw new AssertionError(); 56 * }}</pre> 57 * 58 * <p>{@code @AutoOneOf} is explained in more detail in the <a 59 * href="https://github.com/google/auto/blob/main/value/userguide/howto.md#oneof">user guide</a>. 60 * 61 * @author Chris Nokleberg 62 * @author Éamonn McManus 63 */ 64 @Retention(RetentionPolicy.CLASS) 65 @Target(ElementType.TYPE) 66 public @interface AutoOneOf { 67 /** Specifies an enum that has one entry per variant in the one-of. */ value()68 Class<? extends Enum<?>> value(); 69 } 70