Debian Codegraph @

chunkio-processor/src/com/android/tools/chunkio/processor/ChunksCollector.java

raw
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
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 com.android.tools.chunkio.processor;
18
19 import com.android.tools.chunkio.Chunk;
20
21 import javax.lang.model.element.Element;
22 import javax.lang.model.element.Modifier;
23 import javax.lang.model.element.TypeElement;
24 import javax.lang.model.element.VariableElement;
25 import javax.lang.model.util.ElementFilter;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Set;
29
30 class ChunksCollector {
31 private final TypeElement element;
32 private final ErrorHandler errorHandler;
33
34 ChunksCollector(TypeElement element, ErrorHandler errorHandler) {
35 this.element = element;
36 this.errorHandler = errorHandler;
37 }
38
39 /**
40 * Finds all the fields in the specified type elememt that are annotated
41 * with {@link Chunk}. The chunk annotations are wrapped in a {@link FieldChunk}
42 * to provide easy access to the field's type and name.
43 *
44 * Only valid fields are returned, others are ignored. A field is valid if it:
45 * - is annotated with {@link Chunk}
46 * - is not final
47 * - is not private
48 * - is not static
49 */
50 List<FieldChunk> collect() {
51 List<? extends Element> enclosedElements = element.getEnclosedElements();
52 List<VariableElement> fields = ElementFilter.fieldsIn(enclosedElements);
53
54 List<FieldChunk> chunks = new ArrayList<>();
55 for (VariableElement field : fields) {
56 Chunk chunk = field.getAnnotation(Chunk.class);
57 if (chunk != null && validate(field)) {
58 chunks.add(FieldChunk.from(chunk, field));
59 }
60 }
61
62 return chunks;
63 }
64
65 private boolean validate(VariableElement field) {
66 Set<Modifier> modifiers = field.getModifiers();
67 if (modifiers.contains(Modifier.FINAL)) {
68 errorHandler.error(element, "Field %s in class %s is final", field.getSimpleName());
69 return false;
70 } else if (modifiers.contains(Modifier.PRIVATE)) {
71 errorHandler.error(element, "Field %s in class %s is private", field.getSimpleName());
72 return false;
73 } else if (modifiers.contains(Modifier.STATIC)) {
74 errorHandler.error(element, "Field %s in class %s is static", field.getSimpleName());
75 return false;
76 }
77 return true;
78 }
79 }