BT

JDK 7: What Frequently Rewritten Methods Should be Included in java.util.Objects?

by Ryan Slobojan on Sep 11, 2009 |

In preparation for the arrival of a new class in JDK7 called java.util.Objects which will contain frequently-written utility methods, Joe Darcy of Sun has put out a request to the OpenJDK core-libs-dev group for ideas on what methods should be contained in this class. InfoQ would like to pass this request along to the wider Java community.

In his initial post, Darcy highlighted a couple of potential methods which could be useful in this class:

  • A null-safe equals(arg1, arg2) method which returns true if both arguments are null, false if only one is null, and arg1.equals(arg2) otherwise
  • A set of compareTo(arg1, arg2) methods for all primitive types (int, long, etc)

Some other suggestions came from Andrew John Hughes, including:

  • toString(arg), which would write out via reflection all of the fields inside the object to the returned output string
  • A utility implementation of the clone() method

Martin Buchholz also proposed a null-safe hashCode() implementation, which would return 0 for a null object.

Stephen Colebourne created a long list of proposed methods for this class, primarily by choosing existing methods from the Apache Commons Lang utility classes. Some of those proposed include:

  • min(comparable1, comparable2) and max(comparable1, comparable2), which would be null-safe and which would return the smallest/largest non-null object (or null if both arguments were null)
  • defaultNull(obj, defaultValue) which would return the defaultValue object if obj was null

What are your thoughts? What methods should be added to java.util.Objects?

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

int, long? java.util.Primitives? by Ronald Miura

I don't think that java.util.Objects is the right place to put methods to manipulate primitives... maybe java.util.Primitives?

More methods by Thomas Mueller

boolean isNullOrEmpty(String s)

Those here should be in String, non-regexp versions:
String[] String.splitAt(char separatorChar, boolean trim)
String String.replaceAllExact(String before, String after)

byte[] String.convertHexToBytes()
String String.convertBytesToHex(byte[] value)

byte[] serialize(Object obj)
Object deserialize(byte[] data)

Re: More methods by Thomas Mueller

boolean isNullOrEqual(Object a, Object b)
so instead of
Objects.isNullOrEmpty(s) use Objects.isNullOrEqual(s, "")

stupid idea by Stephan Oudmaijer

Why should a new set of utility classses be included in Java 7? Just use jakarta commons, leave the JDK alone please!!!!

Just another bad idea IMHO, include stuff that does matter!

Copy Apache Commons by Dyego Carmo

Please... copy all thinks of Apache Commons...

This collection is very usefull !!!!

A proxy could be far more useful than a clone by Mario Fusco

The possibility to proxy any kind of object could allow to natively implement some pattern typical of aspect oriented programming.

Moreover I believe that projects like lambdaj ( code.google.com/p/lambdaj/ ) demonstrate very well how a smart use of proxy and reflection allows to easily enrich the language and make it more readable through DSL.

Re: Copy Apache Commons by Eirik Maus

+1 (if that's the max allowed plusses in one post)

Re: Copy Apache Commons by Thomas Mueller

-1 to copy all of Apache Commons. That would be bloat, delay releasing JDK 7, and add many bugs.

Re: Copy Apache Commons by George Petrov

What's the point of copying Apache Commons if it already exists?

My 3 thoughts by William H

1) Might be asking a lot but my wish would be a diff engine for Java beans similar to windiff. Basically something that given a pair of beans can spit something out that showed me what all the differences were. I've written something like this before (sally for a proprietary company so I can't share the code) and it isn't that hard to do but a properly maintained one would be really handy. It’s the sort of thing that when writing auditing for an app can save you a ton of time.

2) Rather less interesting every project I've ever done seems to need an isNullOrEmptry check for strings – i.e:

public static boolean isNullOrEmpty(String text) {

if(text == null || "".equals(text.trim())) {
return true;
}
return false;
}

Hardly rocket science I know…

3) Most of the other suggestions on the original post seem quite sensible to me apart from all the null masking stuff that Colebourne wants to introduce. I don't see much in adding everything from the commons collection.

Re: Copy Apache Commons by James Richardson

Please don't - most of apache software is horribly implemented and has that horrible horrible log4j everywhere. (actually i don't blame log4j - it works fine! - but libraries shouldn't use it!!! send events round the place please)

More than this: why bloat with stuff thats already in existence?

this just strikes me as more fiddling while the real important stuff goes ignored. see "project coin" for more twiddling...

... by Martin Krüger

A null-safe equals(), a clone() method and an hashCode() implementation are worth a discussion, but the other suggestions belongs to other (utility) classes then java.lang.Object.

Format of output in "toString(arg)" call by Blue Diamond

The idea of toString(arg) returning all of the fields inside the object 'arg' is a good idea. I am assuming that it is recursive i.e., toString() will be called on the nested/contained objects if any.

Question is, what will be the format of the output string?

Adding a capability to specify a format viz., XML, YAML/JSON etc. can prove the toString(x) be very helpful. Is this thought about?

If being able to print object on console is the only goal, then YAML/JSON can be a default choice and being able to support XML can also provide a handy solution in serialization of objects for the users.

Bad idea by Andriy Tsykholyas

This is a bad idea. It would just increase the bloat in JDK. And those methods won't be used by majority of developers. I'm developing for years and need for such methods is so rare that it does not worth to put them into Object.
This also violates KISS principle.

A safe cast method might be useful by Gregg Saffell

I occasionally find myself writing

if (obj instanceof MyClass)
{
MyClass mc = (MyClass)obj;
mc.mcMethod();
}

I wonder if Object could be enhanced to allow for something like:

obj.as(MyClass.class).mcMethod();

This of course begs the question, what if obj is not an instance of MyClass? In that case the statemtent would be ignored. Now I suppose if the statement were a declaration (e.g., int y = obj.as(MyClass.class)...) then the statement couldn't be ignored, in that case, it would have to be treated as if it had been written just "int y;".

Objects by Jonathan Locke

It's not an OO thing to do. If you're going to add Object related functionality, it belongs in Object (and if you really want to make me happy, implement mix-ins so we can add our own functionality to any object). The only really useful additions I can think of to Object would be:

boolean Object.safeEquals(Object)
Bytes Object.size() (see wicket for Bytes object and implement as deep sizeof using instrumentation API)

Since Java doesn't have mix-ins (particularly dynamic ones), it might be interesting to allow meta-data object associations:

Object.set(MetaData.Key<T> value)
T Object.get(MetaData.Key<T>)

(this would be implemented with a MetaData object map (ala com.locke.library.utilities.metadata in twenty-six-wicket-tricks on google code) on the side (adding no instance fields to Object, obviously)).

Also, I think a MutableObject<T> would be a nice thing to have in the java core. I implement that one almost every project.

And, BTW, I think making Package work 100% of the time in Class would be of some benefit. We have a workaround in Wicket called PackageName, but that code is undesirable.

There are a number of missing methods in String and List (the obvious first() and last() methods are missing, for example), which could be added. I especially would like to have easy String path-like parsing with:

String String.afterFirst(char)
String String.afterLast(char)
String String.beforeFirst(char)
String String.beforeLast(char)

could also use:

String String.capitalize(String)
String String.decapitalize(String)

and a more efficient replace (that doesn't use regexps), and I'd like this one too:

String String.stripEnding(String ending)

oh, and while you're at it, i'd like member reflection constants like xyz.field and xyz.method.</t></t></t>

Re: Copy Apache Commons by Luis Espinal

What's the point of copying Apache Commons if it already exists?


In some orgs, you are not allowed to add 3rd party jars - as stupid as it might sound, that's reality. Having some or all of the great functionality from apache commons will greatly help. Plus it would consolidate that functionality into one place.

Consider Swing's threadWorker - IIRC it started as a 3rd party lib, and it is now part of the JDK. Good stuff that is more or less a de-facto stardard should be moved into the JDK.

Re: Copy Apache Commons by Luis Espinal

Please don't - most of apache software is horribly implemented and has that horrible horrible log4j everywhere. (actually i don't blame log4j - it works fine! - but libraries shouldn't use it!!! send events round the place please)

More than this: why bloat with stuff thats already in existence?

this just strikes me as more fiddling while the real important stuff goes ignored. see "project coin" for more twiddling...


Uh, did you configure log4j so that it doesn't send events everywhere? The only time "I" see the commons stuff sending log4j messages is when "I" EXPLICITILY configure it to do so, for debugging purposes.

Re: Bad idea by Luis Espinal

This is a bad idea. It would just increase the bloat in JDK. And those methods won't be used by majority of developers. I'm developing for years and need for such methods is so rare that it does not worth to put them into Object.
This also violates KISS principle.


What, you have never had a need for implementing null-safe comparators, formatters, bean property copiers, predicated/filtering collections? Never had a need to reduce re-inventing some or all of the wheels when doing those?

Re: Bad idea by adrian collheart

This is a bad idea. It would just increase the bloat in JDK. And those methods won't be used by majority of developers. I'm developing for years and need for such methods is so rare that it does not worth to put them into Object..


Luckily for you that also isn't the case here. The mentioned utility methods will end up in java.util.Objects, which is distinct from java.lang.Object. But you knew that, didn't you?

Re: Bad idea by Andriy Tsykholyas

Luckily for you that also isn't the case here. The mentioned utility methods will end up in java.util.Objects, which is distinct from java.lang.Object. But you knew that, didn't you?


No, I missed the package. My bad :)

Re: Bad idea by Andriy Tsykholyas

What, you have never had a need for implementing null-safe comparators, formatters, bean property copiers, predicated/filtering collections? Never had a need to reduce re-inventing some or all of the wheels when doing those?

Yes, never had a need for all of them. Still I had need for some of them, but those were really rare cases. In such cases either own code or existing non-JDK libraries can be easily used.

Objects by Nikolay Tsankov

+1 for:
byte[] serialize(Object obj)
Object deserialize(byte[] data)

Also:
String dump(Object o)
Making a best effort to present the object in human readable form, similar to Eclipse's debug view, useful for logging at debug level.

toJSON() by Pedro Fracarolli

It'd be nice to have a String toJSON(Object) method. It'd get all the members' values by calling the getters via reflection and using the getter name - the "get" prefix to name the output JSON attributes.

Re: Bad idea by Rodrigo Lopes

If they wer already in the JDK, you would not need to include other libs to your project

Re: Bad idea by Andriy Tsykholyas

If they wer already in the JDK, you would not need to include other libs to your project


Sure. But you can't put everything into JDK. Libs are exactly for this purpose. JDK should include only the most commonly needed functionality, the rest should be in libs. In my opinion this is not the most commonly needed functionality. And I believe JDK already contains too much functionality which can reside in external/additional libs well.
At the same time there are areas where Java is weak (like closures or multimedia). So, I think JDK guys should concentrate on those areas (because only they can do this). And not implement in JDK functionality which is already available in external libs.

Re: Bad idea by William H


At the same time there are areas where Java is weak (like closures or multimedia). So, I think JDK guys should concentrate on those areas (because only they can do this). And not implement in JDK functionality which is already available in external libs.


Taking your point about JDK containing too much functionality which can reside in external libs multimedia seems to me to be an example of something better residing outside the JDK since it wouldn't be well served by the long release cycles of the full JDK. JavaFX, whilst it still has a way to go, is doing a pretty good job in this area in my view. With closures Sun obviously wanted to add them in but didn't feel it has enough support from Java devs as a whole to risk it so really we only have ourselves to blame here.

Dealing with nulls by Eric Francis

Two suggestions:

First would be compile-time null-safety checking. There are already code analysis tools which can do analysis on the code to and determine code which could be not null-safe. Perhaps if the compiler would be able to include similar analysis and raise at least a warning if it finds any code which isn't null-safe. Eiffel's latest version includes similar checking (they use void reference in place of null reference), and the whitepaper on the subject at: docs.eiffel.com/sites/default/files/void-safe-e....

Second would be to have null be the ultimate object which implements all classes and does nothing and returns null in all cases (with certain exceptions if dealing with multiple null objects). While this would remove the NullPointerException (all cases would just do nothing and return null), I wouldn't recommend this without at least the compile-time warnings as described in my first suggestion, as this would be so prone to errors in unchecked code. Another difficulty of this would be determining (in a semi-general way) in what cases operations on the null object would return null and in what cases operations would return some other value (for instance null+1 -> null, while null==1 -> false, or sum(1,2,3,null,5) -> 11).

Of course I do like the other suggestions for making more methods null-safe by handling null inside the core code rather than expecting developers to have to include all-too-redundant null checks throughout their code. Null shouldn't be considered something to be avoided resulting in catastrophes when it is accidentally used, but as a valid representation of nothing or no value to be handled gracefully whenever it is present. It's kind of like 0 in that way - 0 being a representation of how many apples you have after someone takes your last apple.

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

28 Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT