2016-05-07 44 views
0

假設我們有一個包含兩個重載主方法的類。調用超載主方法

public class MyClass { 
    public static void main(int x){ 
    System.out.println("(int x)version"); 
    } 

    public static void main(String[] args){ 
    System.out.println("(String[] args)"); 
    } 
} 

那麼,如何在運行程序時調用(int x)版本?

回答

0

是的,你可以重載主

不,你不能啓動你的程序調用過載, JVM會叫的主要特徵主要(字串[] args)超載。

//JVM will call this method manually if you want 
public static void main(String[] args,int a){ 
// some code 
} 

//JVM will call this method to start your program 
public static void main(String[] args){ 
// some code 
} 
+0

好的,所以這個特殊的方法有特殊的重載語義。它可以被重載,但不能使用java 來調用。感謝Danito瞭解我的問題。 – Nealesh

2

的唯一方法是調用它,你會打電話給任何其他靜態方法,例如:

public static void main(String[] args) { 
    // call other "main" 
    main(5); 
} 

的問題是,真正的主要方法的方法簽名必須精確匹配什麼JVM期待因爲它是。所有其他的「main」方法重載與JVM的任何其他方法一樣,不會成爲自動程序啓動的位置。

3

MyClass.main(5)

是如何調用它的例子。


如果自動希望被稱爲main(int)方法,只是從main(String[])調用它。我假設你想讓java像輸入一樣處理輸入。這裏是一個辦法做到這一點

public static void main(int ... ints) { 
    // Process 
} 

public static void main (String[] args) { 
    main(Arrays.stream(args).mapToInt(Integer::parseInt).toArray()); 
} 
+0

我知道如何調用方法,我懷疑是否有可能使用java命令調用重載main方法。我知道我不確切。 :-) – Nealesh

+0

@Nealesh對不起,我明白,但沒有回答。不,這是不可能的,JVM將搜索'public static void main(String [])',如果找不到則拋出一個錯誤。 –

+0

好的,謝謝您的確認。 – Nealesh