我試圖宣告一個變數,它接受任何型別的方法參考Function<AnyObject, AnyObject or Any Enum>
。這個方法參考將在映射器中使用,我接受一些輸入并通過呼叫另一個物件的方法來映射相應的值。
@Data //Lombok
public class ReferenceSample<T, R> {
private final Function<T, R > methodReference; //應該能夠接受任何方法參考。
}
以下是可能的方法
public class Common {
public static String getMethod1(String a) {
//Process
return " result1";
}
public static SomeEnum getMethod2(String b) {
//Process
return SomeEnum.DATA。
}
當我試圖創建這個物件時
new ReferenceSample(Common::getMethod1)。
我得到如下錯誤
java: incompatible types: invalid method reference
不兼容的型別:java.lang.Object不能轉換為java.lang.String
uj5u.com熱心網友回復:
你需要對通用型別進行專業化處理,如下所示。
public class Reference
{
public static void main (String[] args)
{
Reference app = new Reference ()。
app.test ();
}
private void test ()
{
int[] row = {1, 1, 5, 2, 4}。
System.out.println ("輸入。" Arrays.toString (row))。
//這失敗了,因為通用型別沒有被指定。
ReferenceSample rs1 = new ReferenceSample (Common::getMethod1)。
//這可以編譯,但并不專業。
ReferenceSample<?, ?> rs2 = new ReferenceSample<> (Common::getMethod1)。
//這是首選,因為它精確地指定了型別。
ReferenceSample<String, String> rs3 = new ReferenceSample<> (Common::getMethod1)。
}
}
class ReferenceSample<T, R>
{
public Function<T, R> methodReference; //應該能夠接受任何方法參考。
public ReferenceSample (Function<T, R> methodReference)
{
this.methodReference = methodReference。
}
}
class Common
{
public static String getMethod1 (String a)
{
//Process
return " result1";
}
public static String getMethod2 (String b)
{
//Process
return " "/span> b " "/span>。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/318641.html
標籤:
