[英]How do I correctly restrict a generic interface to extend Number class in Java and be able to run it in another class?
我試圖了解如何擴展接口並在另一個 class 中使用它,但每次編譯器都會拋出轉換錯誤。 我曾嘗試在 printResult 方法中使用通配符,但它不起作用。 這里可能是什么問題? 它僅適用於 Integer。
public interface Computable <T extends Number>
{
public T compute(T x, T y);
}
------------------------------------------------------------
public class TestComputable
{
public static void main(String[] args)
{
Computable<Float> comp;
comp = (x, y) -> x + y;
printResult(comp);
}
}
public static void printResult(Computable compIn)
{
System.out.println("The result is: " + compIn.compute(10, 5));
}
這是編譯器實際上試圖通過發出有關使用原始類型的警告來幫助您的地方:如果您將printResult
方法更改為使用正確的類型參數,如下所示:
public static void printResult(Computable<Float> compIn) { // instead of Computable compIn
那么編譯器會在編譯時顯示錯誤:
// Now the compiler throws error:
// the method compute(Float, Float) is not applicable for the arguments (int, int)
System.out.println("The result is: " + compIn.compute(10, 5));
這就是為什么您應該始終避免使用原始類型的原因,編譯器可以推斷出正確的類型綁定。
現在我們有了編譯錯誤消息,我們知道問題出在哪里:arguments 10
和5
是int
值,而接口Computable
需要Float
值,因此您可以將它們修復為浮點值:
System.out.println("The result is: " + compIn.compute(10f, 5f));
您的代碼僅適用於 Integer,因為您將 Integer arguments 傳遞給 Computable。
如果要傳入例如“整數的浮點等效項”,則需要傳入 Function 以將 Integer 轉換為浮點數; 更一般地說,如果您想傳入“整數的 T 等效項”,則需要傳入 Function 以將 Integer 轉換為 T:
public static <T extends Number> void printResult(Computable<T> compIn, Function<? super Integer, ? extends T> fn)
{
System.out.println("The result is: " + compIn.compute(fn.apply(10), fn.apply(5)));
}
並像這樣調用:
printResult(comp, Integer::floatValue);
或者,您可以顯式傳入正確類型的 arguments:
public static <T extends Number> void printResult(Computable<T> compIn, T a, T b) {
// ... Something with compln.compute(a, b)
}
並像這樣調用:
printResult(comp, 10.f, 5.f);
您可以在不傳遞其他參數的情況下完成這項工作的唯一方法是只接受一個可以接受任何數字的Computable
,或者至少可以接受您傳入的類型的 arguments:
public static void printResult(Computable<Number> compIn) { ... }
public static void printResult(Computable<Integer> compIn) { ... }
public static void printResult(Computable<? super Integer> compIn) { ... }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.