Groovy Reflection: Fields and Properties
Eine simple Methode, um für eine übergebene Klasseninstanz ein Logging aller vorhandenen (öffentlichen) Felder und Methoden zu ermöglichen:
static Object invoke(Object instance) {
Class inClass = instance.class
def filtered = ["metaClass","class","active","__\$stMC"]
String prefix = "PL: ${inClass.name}: "
long pad = 0
long l = 0
String n
String v
Map<String, String> m = [:]
inClass.fields.each() {
Field f ->
try {
n = f.name
v = f.get(instance)
if(!(n in filtered) && (v != null)) {
n = "F: ${n}"
l = n.length()
if(l > pad) {
pad = l
}
m[n] = v
}
}
catch (Exception e) {
println(e)
}
}
instance.properties.each {
prop, val ->
if(!(prop in filtered) && (val != null)) {
prop = "P: ${prop}"
l = prop.length()
if(l > pad) {
pad = l
}
m[prop] = val
}
}
pad = pad + prefix.length() + 3
m.each {
key, val ->
println("${prefix}<${key}> ".padRight(pad, ' ') + "<${val}>")
}
}
0 Kommentare