What methods should go into a java.util.Objects class in JDK 7?
Rémi Forax
forax at univ-mlv.fr
Thu Sep 10 00:04:08 UTC 2009
Le 10/09/2009 01:43, Andrew John Hughes a écrit :
> 2009/9/10 Rémi Forax<forax at univ-mlv.fr>:
>
>> Le 09/09/2009 23:22, Andrew John Hughes a écrit :
>>
>>> Given you've listed utility methods for two Object methods, equals and
>>> hashCode, toString seems an obvious one to handle as well:
>>>
>>> public static String toString(Object o)
>>> throws IllegalAccessException
>>> {
>>> Class<?> c = o.getClass();
>>> StringBuilder b = new StringBuilder(c.getName());
>>> b.append("[");
>>> for (Field f : c.getDeclaredFields())
>>> {
>>> f.setAccessible(true);
>>> b.append(f.getName() + "=" + f.get());
>>> b.append(",");
>>> }
>>> b.replace(b.length() - 1, b.length(), "]");
>>> return b.toString();
>>> }
>>>
>>> Maybe there's also a useful utility implementation of clone too, but I
>>> can't think of one offhand.
>>>
>>>
>> Arghhh,
>>
>> b.append(f.getName() + "=" + f.get());
>>
>> shoud be
>>
>> b.append(f.getName()).append("=").append(f.get(o));
>>
>>
>> And I think there is a problem if the object has no field.
>>
>> Rémi
>>
>>
> Yeah, it was meant to be just a proof of concept, not bulletproof
> efficient code for actual use, but thanks for the code review :)
> Gives output something like: Utils[bing=5,boom=boom,isDone=false]
> I end up writing so many toString methods that are return
> getClass().getName() + "[field1=" + field + ",field2=" + field2 + "]";
> that it would make things easier. Not as efficient as implementing it
> yourself, agreed, but I find I usually call these methods only when
> debugging anyway.
>
I agree about the debugging purpose, that why I don't agree
with Kevin when he said that java.util.Objects should not use
reflection.
Perhaps the method can be renamed to: toDebugString.
Rémi
PS: the code above also forget inherited fields.
More information about the core-libs-dev
mailing list