13 May 2004 08:44
Re: [groovy-dev] patch for Object.eachPropertyName()
Hi John
Thanks for the patch.
We have a MetaProperty object in the groovy.lang package (like the
MetaClass and MetaMethod objects) which I was hoping the eachProperty()
method would iterate through. e.g. the eachProperty() method could
iterate through the MetaClass.getMetaProperties() collection
e.g.
bean.eachProperty { |p|
println("property name ${p.name} is of type ${p.type} with value
${p.getProperty(bean)}")
}
One downside of this is that the last expression is a little verbose; a
BeanProperty represents the property type for any instance and so you
have to pass in an instance to get the value out. So maybe the
eachProperty() method might generate a little wrapper object which
hardwires in the bean you're iterating over so that we could do things
like
bean.eachProperty { |p|
println("property name ${p.name} is of type ${p.type} with value
${p.value} on bean ${p.bean}")
}
Maybe we also need a version of this method which returns a list of
properties...
bean.properties().findAll { it.type == String.class }.sort { it.name
}.each { println("${it.name} = ${it.value}") }
On 13 May 2004, at 03:51, John Stump wrote:
> Hi all,
>
> I have here a little patch to implement the eachPropertyName()
> method on all Objects, which is mentioned in the TODO.txt file.
> This goes in the DefaultGroovyMethods.java file. I borrowed the
> property retrieving logic from the dump() method. With this, you
> can do something like this:
>
> a = new SomeClass()
> a.eachPropertyName { println "${it} = ${a[it]}" }
>
> I was also going to tackle the eachProperty() method mentioned
> along with eachPropertyName(), but I wasn't sure what the
> closure parameter(s) were.
>
> I thought there was a JIRA issue for this, but I couldn't find
> it...
>
>
> public static void eachProperty(Object self, Closure closure) {
> Class klass = self.getClass();
> boolean groovyObject = self instanceof GroovyObject;
>
> while(klass != null) {
> Field[] fields = klass.getDeclaredFields();
>
> for(int i = 0; i < fields.length; i++) {
> final Field field = fields[i];
>
> if((field.getModifiers() & Modifier.STATIC) == 0) {
> if(groovyObject &&
> field.getName().equals("metaClass")) {
> continue;
> }
>
> AccessController.doPrivileged(
> new PrivilegedAction() {
> public Object run() {
> field.setAccessible(true);
> return null;
> }
> });
>
> // call the closure with this property name
> closure.call(field.getName());
> }
> }
>
> // get the next parent class
> klass = klass.getSuperclass();
> }
> }
>
>
>
>
>
> __________________________________
> Do you Yahoo!?
> Yahoo! Movies - Buy advance tickets for 'Shrek 2'
> http://movies.yahoo.com/showtimes/movie?mid=1808405861
> _______________________________________________
> groovy-dev mailing list
> groovy-dev@...
> http://lists.codehaus.org/mailman/listinfo/groovy-dev
>
>
James
-------
http://radio.weblogs.com/0112098/
RSS Feed