我在这里遇到了一件有趣的事情。这不是问题,我只是对优先顺序感到好奇。让我们转到代码:
我在同一个类上有这两个方法:
1- public void method1(String a, String...b){
2- System.out.println(a + "===" + b[0]);
3- }
4-
5- public void method1(String a, String b){
6- method1(a, b);
7- }
8-
9- public static void main(String[] args) {
10- Teste t = new Teste();
11- t.method1("a", "b");
12- }
在这里运行测试,我看到第 11 行对 method1
的调用将调用第 5 行定义的 method1
然后它会进行自调用,因此java.lang.StackOverflowError
。我的问题是关于这些方法的优先顺序调用,因为第 1 行的 method1
在第 5 行收到 String, String[]
和 method1
理论上接收 String, String
如果我只想将第二个参数上的一个字符串传递给两种方法,它们接收相同的参数。
我知道在这种情况下,要调用第 1 行的特定方法,仅使用一个字符串作为第二个参数,我必须执行 method1("someString", new String[]{"someString"});
我想知道这个优先顺序调用是否有任何解释(或文档)。上面写着这样的话:
“在具有相同参数的方法定义中,其中一个方法接收一个对象,另一个方法接收同一对象的数组,如果您只传递一个参数,将执行它的方法将是只接收一个对象的方法而不是接收该对象数组的那个”
最佳答案
我想答案可以在15.12.2. Compile-Time Step 2: Determine Method Signature中找到:
There may be more than one such method, in which case the most specific one is chosen. The descriptor (signature plus return type) of the most specific method is one used at run time to perform the method dispatch.
通过它并查看 examples以获得更好的解释。
关于java - 优先方法调用顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20496116/