in sample/plugins-compiler/plugins-compiler/java/src/main/java/com/uber/crumb/sample/pluginscompiler/PluginsCompiler.java [89:171]
public void consume(
CrumbContext context,
TypeElement type,
Collection<? extends AnnotationMirror> annotations,
Set<? extends Map<String, String>> metadata) {
// Must be an abstract class because we're generating the backing implementation.
if (type.getKind() != ElementKind.CLASS) {
context
.getProcessingEnv()
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
"@"
+ PluginPoint.class.getSimpleName()
+ " is only applicable on classes when consuming!",
type);
return;
} else if (!type.getModifiers().contains(ABSTRACT)) {
context
.getProcessingEnv()
.getMessager()
.printMessage(Diagnostic.Kind.ERROR, "Must be abstract!", type);
}
// Read the pluginpoint's target type, e.g. "MyPluginInterface"
PluginPoint pluginPoint = type.getAnnotation(PluginPoint.class);
TypeMirror targetPlugin = getTargetPlugin(pluginPoint);
// List of plugin TypeElements
ImmutableSet<TypeElement> pluginClasses =
metadata
.stream()
.map(data -> data.get(METADATA_KEY))
.map(
pluginClass ->
context.getProcessingEnv().getElementUtils().getTypeElement(pluginClass))
.filter(
pluginType ->
context
.getProcessingEnv()
.getTypeUtils()
.isAssignable(pluginType.asType(), targetPlugin))
.collect(toImmutableSet());
FieldSpec pluginsSetField =
FieldSpec.builder(
ParameterizedTypeName.get(ClassName.get(Set.class), TypeName.get(targetPlugin)),
"PLUGINS",
PUBLIC,
STATIC,
FINAL)
.initializer(CodeBlock.of("new $T<>()", LinkedHashSet.class))
.build();
CodeBlock.Builder staticInitBlock = CodeBlock.builder();
pluginClasses.forEach(
plugin ->
staticInitBlock.addStatement(
"$N.add(new $T())", pluginsSetField, TypeName.get(plugin.asType())));
TypeSpec generatedClass =
TypeSpec.classBuilder("Plugins_" + type.getSimpleName().toString())
.addModifiers(PUBLIC, FINAL)
.superclass(TypeName.get(type.asType()))
.addField(pluginsSetField)
.addStaticBlock(staticInitBlock.build())
.build();
try {
JavaFile.builder(MoreElements.getPackage(type).getQualifiedName().toString(), generatedClass)
.build()
.writeTo(context.getProcessingEnv().getFiler());
} catch (IOException e) {
context
.getProcessingEnv()
.getMessager()
.printMessage(
Diagnostic.Kind.ERROR,
"Failed to write generated plugins mapping! " + e.getMessage(),
type);
}
}