1 /* 2 * Copyright (C) 2013 The Dagger Authors. 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 17 package dagger.internal.codegen; 18 19 import com.google.common.collect.ImmutableList; 20 import java.util.List; 21 import javax.lang.model.element.AnnotationValue; 22 import javax.lang.model.element.AnnotationValueVisitor; 23 import javax.lang.model.type.TypeMirror; 24 import javax.lang.model.util.SimpleAnnotationValueVisitor8; 25 26 /** Utility methods for working with {@link AnnotationValue} instances. */ 27 final class MoreAnnotationValues { 28 /** 29 * Returns the list of values represented by an array annotation value. 30 * 31 * @throws IllegalArgumentException unless {@code annotationValue} represents an array 32 */ asAnnotationValues(AnnotationValue annotationValue)33 static ImmutableList<AnnotationValue> asAnnotationValues(AnnotationValue annotationValue) { 34 return annotationValue.accept(AS_ANNOTATION_VALUES, null); 35 } 36 37 private static final AnnotationValueVisitor<ImmutableList<AnnotationValue>, String> 38 AS_ANNOTATION_VALUES = 39 new SimpleAnnotationValueVisitor8<ImmutableList<AnnotationValue>, String>() { 40 @Override 41 public ImmutableList<AnnotationValue> visitArray( 42 List<? extends AnnotationValue> vals, String elementName) { 43 return ImmutableList.copyOf(vals); 44 } 45 46 @Override 47 protected ImmutableList<AnnotationValue> defaultAction(Object o, String elementName) { 48 throw new IllegalArgumentException(elementName + " is not an array: " + o); 49 } 50 }; 51 52 /** 53 * Returns the type represented by an annotation value. 54 * 55 * @throws IllegalArgumentException unless {@code annotationValue} represents a single type 56 */ asType(AnnotationValue annotationValue)57 static TypeMirror asType(AnnotationValue annotationValue) { 58 return AS_TYPE.visit(annotationValue); 59 } 60 61 private static final AnnotationValueVisitor<TypeMirror, Void> AS_TYPE = 62 new SimpleAnnotationValueVisitor8<TypeMirror, Void>() { 63 @Override 64 public TypeMirror visitType(TypeMirror t, Void p) { 65 return t; 66 } 67 68 @Override 69 protected TypeMirror defaultAction(Object o, Void p) { 70 throw new TypeNotPresentException(o.toString(), null); 71 } 72 }; 73 MoreAnnotationValues()74 private MoreAnnotationValues() {} 75 } 76