![](/img/trans.png)
[英]java - passing type of array of Vectors argument, to function as a Class<T> type parameter
[英]Java: passing an argument with a different type to a function
在Java中,假設我們有一個帶參數double a
的函數。 如果我傳遞一個整數作為參數,它是否有效? (我的意思是,是否存在隱式轉換?)在相反的情況下:如果我有一個整數作為參數,我傳遞一個double?
不幸的是,我目前無法編譯我的代碼,我想檢查這個斷言。 感謝您的關注。
有關Method Invocation Conversion
詳細信息,請參閱JLS - 第5.3節 。
方法調用上下文允許使用以下之一:
- an identity conversion (§5.1.1) - a widening primitive conversion (§5.1.2) - a widening reference conversion (§5.1.5) - a boxing conversion (§5.1.7) optionally followed by widening reference conversion - an unboxing conversion (§5.1.8) optionally followed by a widening primitive conversion.
因此,根據規則#2 ,您的第一次調用( int
to double
)將正常工作。
但根據同一部分中引用的聲明,第二次調用( double
to int
)將給出編譯器錯誤 : -
如果表達式的類型無法通過方法調用上下文中允許的轉換轉換為參數的類型,則會發生編譯時錯誤。
因為你可以將double設置為一個整數,那么整數作為參數就可以使用double作為參數。 其他方式失敗。 在這種情況下,您需要將double轉換為int。 同樣適用於普通受讓人,例如......
int i = 6;
double d = 0;
d = i; /* ok
i = d ; /* not ok
你可以通過使你的函數取一個Number
參數來解決這個問題。 這是一個Integer
和Double
都繼承的Object,所以直到Double
數字和Integer
數字的行為相同,這都行。
請注意,基元integer
和double
以及Objects Integer
和Double
之間存在差異。 Java使用自動裝箱在函數調用等中自動在這些類型之間進行轉換。
最初,原始類型會發生原始擴展 。 例如,你想打電話
int input = 5; //int variable;
apply(input); //calling method with int value.
但是你的類不包含一個方法,該方法接受int,因此編譯器將進行原始擴展 。 它將檢查任何帶有java long參數的apply方法是否存在。 如果存在,將調用該方法。 如果不是,它將檢查是否存在浮動參數的應用 ,然后它將被選中。 如果這也沒有找到它將尋找申請與雙參數。
public void apply(long input) {
System.out.println("long"); // first pick by the compiler.
}
public void apply(float input) {
System.out.println("float"); // if above method not found this will be selected.
}
public void apply(double input) {
System.out.println("double"); // above two methods not present this will be selected.
}
接下來,如果找不到以上三種方法,那么編譯器將尋找Autoboxing this並嘗試將其轉換為相應的包裝器。 對於int java.lang.Integer的它。所以它會檢查與整數參數適用 。 如果找到這個編譯器將執行此方法。
public void apply(Integer input) {
System.out.println("Integer");
}
最后,如果上述情況都不存在,編譯器將查找名稱為apply的任何方法,該方法接受int ...或Integer ...並調用該方法。
public void apply(int... input) {
System.out.println("int...");
}
如果您的類僅包含以下兩種方法
public void apply(long input) {
System.out.println("long");
}
public void apply(float input) {
System.out.println("float");
}
並且您希望將double值傳遞給此方法,它不會編譯。
double input = 5d;
apply(input);
// The method apply(long) in the type YourClass
//is not applicable for the arguments (double
如果你想做那項工作,你必須輸入強制轉換為你的方法可以接受的東西。
apply((int) input);
然后編譯器將嘗試通過精確類型或原始擴展或自動裝箱或陣列匹配方式找到匹配。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.