public final class NameAllocator extends Object
NameAllocator nameAllocator = new NameAllocator();
for (MyProperty property : properties) {
nameAllocator.newName(property.name(), property);
}
nameAllocator.newName("sb", "string builder");
Pass a unique tag object to each allocation. The tag scopes the name, and can be used to look up
the allocated name later. Typically the tag is the object that is being named. In the above
example we use property
for the user-supplied property names, and "string
builder"
for our constant string builder.
Once we've allocated names we can use them when generating code:
MethodSpec.Builder builder = MethodSpec.methodBuilder("toString")
.addAnnotation(Override.class)
.addModifiers(Modifier.PUBLIC)
.returns(String.class);
builder.addStatement("$1T $2N = new $1T()",
StringBuilder.class, nameAllocator.get("string builder"));
for (MyProperty property : properties) {
builder.addStatement("$N.append($N)",
nameAllocator.get("string builder"), nameAllocator.get(property));
}
builder.addStatement("return $N", nameAllocator.get("string builder"));
return builder.build();
The above code generates unique names if presented with conflicts. Given user-supplied properties
with names ab
and sb
this generates the following: @Override
public String toString() {
StringBuilder sb_ = new StringBuilder();
sb_.append(ab);
sb_.append(sb);
return sb_.toString();
}
The underscore is appended to sb
to avoid conflicting with the user-supplied sb
property. Underscores are also prefixed for names that start with a digit, and used to replace
name-unsafe characters like space or dash.Copyright © 2015 Square, Inc.. All rights reserved.