Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public final class FinalRClassBuilder {
...
private static final String[] SUPPORTED_TYPES = {
"anim", "array", "attr", "bool", "color", "dimen", "drawable", "id", "integer", "layout", "menu", "plurals",
"string", "style", "styleable"
};
...
public static void brewJava(File rFile, File outputDir, String packageName, String className)
throws Exception {
CompilationUnit compilationUnit = JavaParser.parse(rFile);
TypeDeclaration resourceClass = compilationUnit.getTypes().get(0);
TypeSpec.Builder result =
TypeSpec.classBuilder(className).addModifiers(PUBLIC).addModifiers(FINAL);
for (Node node : resourceClass.getChildNodes()) {
if (node instanceof ClassOrInterfaceDeclaration) {
addResourceType(Arrays.asList(SUPPORTED_TYPES), result, (ClassOrInterfaceDeclaration) node);
}
}
JavaFile finalR = JavaFile.builder(packageName, result.build())
...
.build();
finalR.writeTo(outputDir);
}
private static void addResourceType(List<String> supportedTypes, TypeSpec.Builder result,
ClassOrInterfaceDeclaration node) {
...
String type = node.getNameAsString();
TypeSpec.Builder resourceType = TypeSpec.classBuilder(type).addModifiers(PUBLIC, STATIC, FINAL);
for (BodyDeclaration field : node.getMembers()) {
if (field instanceof FieldDeclaration) {
FieldDeclaration declaration = (FieldDeclaration) field;
// Check that the field is an Int because styleable also contains Int arrays which can't be
// used in annotations.
if (isInt(declaration)) {
addResourceField(resourceType, declaration.getVariables().get(0),
getSupportAnnotationClass(type));
}
}
}
result.addType(resourceType.build());
}
...
private static void addResourceField(TypeSpec.Builder resourceType, VariableDeclarator variable,
ClassName annotation) {
String fieldName = variable.getNameAsString();
String fieldValue = variable.getInitializer().map(Node::toString).orElse(null);
FieldSpec.Builder fieldSpecBuilder = FieldSpec.builder(int.class, fieldName)
.addModifiers(PUBLIC, STATIC, FINAL)
.initializer(fieldValue);
...
resourceType.addField(fieldSpecBuilder.build());
}
...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment