最具体的构造函数签名

时间:2016-09-01 12:42:12

标签: java methods parameters null signature

给定构造函数:

  1. A(B... params)
  2. A(String param1, B... params)
  3. 当我调用A(null)时,会调用第一个构造函数。有没有办法用参数null调用第二个构造函数,但是没有将null强制转换为String

    编辑: 我在描述我的问题上犯了一些错误,现在应该没问题。

2 个答案:

答案 0 :(得分:1)

你有的地方

A a = new A(null);

这就是出错的唯一情况。 (假设B是具体类型,不是通用的。)你不想要

A a = new A((String)null);
A a = new A("");

然后去寻求最大限度,并添加一个快捷方式构造函数:

A() {
    this((String) null);
}

A a = new A();

它不会阻止new A(null)

答案 1 :(得分:-2)

抱歉,但我没有看到你的问题。

public class A
{
    A(String a)
    {
        System.out.println("constructor(String)");
    }

    A(String a, B... b)
    {
        System.out.println("constructor(String, B...)");
    }

    public static void main(String[] args)
    {
        new A(null, null);
    }

    private static final class B
    {

    }
}
相关问题