在下面的类中,由于对this()
的不明确调用,我在Java8中遇到了编译错误。不过,在Java6中,这个类编译得很好。我知道我可以使用工厂方法之类的方法来重构它,但对于出现问题的实际类,我强烈希望现在就维护当前的API。
有没有人能想出一种不改变外部API就能解决歧义的方法呢?
public class Vararg8 {
public Vararg8(final Object... os) {}
public Vararg8(final boolean b,
final String s,
final int... is) {}
public Vararg8() {
this(true, "test", 4, 5, 6);
}
}
发布于 2016-08-30 20:33:13
试试这个:
public Vararg8()
{
this(true, "test", new int[]{4, 5, 6});
}
发布于 2016-08-30 20:33:20
使用显式int数组应该可以解决您的问题。
public Vararg8() {
this(true, "test",new int[]{ 4, 5, 6});
}
发布于 2016-08-31 05:53:04
您可以在运行时使用泛型来推断类型,但这会将它们转换为盒装形式。这当然是性能神风,如果你在其中做了很多算术,或者必须装箱很多原语,但会让所有现有的代码都工作得很好。
如果您已经在使用对象类型,则此解决方案将不会花费您任何成本。
这看起来像这样:
public<A extends Boolean, B extends String, C extends Integer> Disambiguate(final A booleanPar,
final B stringPar,
final C... integerPar) {System.out.println("Im in the specific one");}
public<T extends Object> Disambiguate(final T... os) {System.out.println("Im in the general one");}
public static void main(String[] args) {
new Disambiguate(true, "test", 4, 5, 6);
}
你可以使用泛型来实现1.5和更高版本的“向后兼容性”,让所有现有的代码都工作得很好,并创建一个新的Api,这样就可以避免将来出现这个问题。
https://stackoverflow.com/questions/39227561
复制相似问题