Skip to content

Instantly share code, notes, and snippets.

@milovtim
Last active February 20, 2017 17:18
Show Gist options
  • Save milovtim/06350dcccc41dd21663ff313f2c69767 to your computer and use it in GitHub Desktop.
Save milovtim/06350dcccc41dd21663ff313f2c69767 to your computer and use it in GitHub Desktop.
Get class FQN and compose builder methods
import groovy.text.SimpleTemplateEngine
import java.lang.reflect.Method
def classFQN = args.length > 0? args[0]: System.exit(1)
Class<?> clazz = Class.forName(classFQN, false, getClass().getClassLoader())
class BuilderTemplateWrapper {
final Class<?> clazz
BuilderTemplateWrapper(Class<?> clazz) {
this.clazz = clazz
}
def getShortName() {
clazz.simpleName + 'Builder'
}
def getMethods() {
clazz.methods.findAll { it.name.startsWith('get') || it.name.startsWith('is')}.collect { Method m ->
def propName = m.name[3..-1]
def propNameLower = propName[0].toLowerCase() + propName[1..-1]
def propType = m.genericReturnType.typeName
"""public ${this.shortName} with$propName(${propType} $propNameLower) {
this.$propNameLower = $propNameLower;
return this;
}
"""
}
}
def getProps() {
clazz.methods.findAll { it.name.startsWith('get') || it.name.startsWith('is')}.collect { Method m ->
def propName = m.name[3..-1]
def propNameLower = propName[0].toLowerCase() + propName[1..-1]
def propType = m.genericReturnType.typeName
"private $propType $propNameLower;"
}
}
}
def text = '''
<% clazz.props.each { p-> %>
$p
<% } %>
<% clazz.methods.each { m-> %>
$m
<% } %>
'''
def engine = new SimpleTemplateEngine()
def result = engine
.createTemplate(text)
.make(clazz: new BuilderTemplateWrapper(clazz))
if (args.contains('clip'))
'xclip -selection clip'.execute().withWriter { Writer w ->
result.writeTo(w)
}
if (args.contains('print'))
println result.toString()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment