I have an old untyped class pre Java1.5 and need t开发者_如何学Pythono 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
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);
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.
精彩评论