Last active
February 20, 2017 17:18
-
-
Save milovtim/06350dcccc41dd21663ff313f2c69767 to your computer and use it in GitHub Desktop.
Get class FQN and compose builder methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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