开发者

Java Generics Refactoring and Ambiguity

开发者 https://www.devze.com 2023-01-11 12:21 出处:网络
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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号