views:

40

answers:

2

I have an old untyped class pre Java1.5 and need to refactor it using Java Generics to get more type security in the code.

Old Code looks like this:

class Foo { 
  void setInput(Object input) {...}
}

Now this input could be some object but it may also be an array, nasty stuff. Making a generic version of it seems not to be trivial, I tried:

class Foo<E> {
  void setInput(E input) {...}
  void setInput(E[] input) {...}
}

The problem is that this is ambiguous for example for calls:

Foo f = Foo<SomeClassyClass>();
f.setInput(null);

Is there some good solution to this problem or do I need to take a completely other approach?

Thanks, Patrick

+6  A: 

This type of ambiguity is not new to generics but can always happen with overloaded methods. You have to cast the null:

Foo<String> f = new Foo<String>();

f.setInput((String[]) null);
f.setInput((String) null);
musiKk
+1 for pointing out this is not specific to generics
Gopi
A much better way to fix is to prefer not to overload. (Also `List<>` is your friend; `[]` less so.)
Tom Hawtin - tackline
The way the new code looks it seems to me that the old `setInput` probably did the distinction whether it got a single element or an array via `instanceof` which is far worse than overloading (but this is just a guess on my side). I always find it nice when some method that takes some `Collection` also is overloaded with a method that takes a single element and uses `Collections.singletonList()` (or equivalent).
musiKk
+1  A: 

In this particular case, you can do:

Foo<SomeClassyClass> f = new Foo<SomeClassyClass>();
f.setInput((SomeClassyClass)null);

or:

Foo<SomeClassyClass> f = new Foo<SomeClassyClass>();
f.setInput((SomeClassyClass[])null);

To solve the ambiguïty.

Maurice Perry