What methods should go into a java.util.Objects class in JDK 7?
Andrew John Hughes
gnu_andrew at member.fsf.org
Wed Sep 9 23:43:57 UTC 2009
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.
--
Andrew :-)
Free Java Software Engineer
Red Hat, Inc. (http://www.redhat.com)
Support Free Java!
Contribute to GNU Classpath and the OpenJDK
http://www.gnu.org/software/classpath
http://openjdk.java.net
PGP Key: 94EFD9D8 (http://subkeys.pgp.net)
Fingerprint: F8EF F1EA 401E 2E60 15FA 7927 142C 2591 94EF D9D8
More information about the core-libs-dev
mailing list