具有泛型方法类型的本地记录

问题描述 投票:0回答:1

为什么无法创建包含与方法的泛型类型对应的字段的本地记录?

不工作示例:

public class Test {

   <T> void foo(T param) {
       record Container(T content) { }
       Container test = new Container(param);
   }
}

工作,但在我看来没有必要:

public class Test {

   <T> void foo(T param) {
       record Container<S>(S content) { }
       Container<T> test = new Container<>(param);
   }
}
java generics record
1个回答
0
投票

您正在

record
方法中创建一个
foo
。这将创建一个新类。如果您使用类型
T
,它将失败,因为此类型可以更改每个方法调用

使用

record Container<S>(S content) { }
时,您将在方法中创建一个临时类型,其作用域与记录的作用域相同。

为了能够使用

T
类型,您可以使用
S
的类型来拍摄实际 T 类型的“照片”,例如:

public class Test {

   <T> void foo(T param) {
       record Container<S extends T>(S content) { }
       Container<T> test = new Container<>(param);
   }
}

在这种情况下,类型

S
应该是类型
T
或其子类。

© www.soinside.com 2019 - 2024. All rights reserved.