传递泛型类型内部类
这是以下示例:
import lombok.Builder;
import lombok.Getter;
import lombok.Singular;
import java.util.List;
@Getter
@Builder
public class GenericsType<T> {
@Singular("entry")
private List<Animal> list;
@Builder
private static class Animal<T> {
T test;
}
public void main(String args[]){
GenericsType.<String>builder()
.entry(Animal.<String>builder().test("my object").build())
.build();
}
}
有没有一种方法可以只传递通用
一次?实际上内部类应该已经知道它的类型。
GenericsType.<String>builder()
.entry(Animal.builder().test("my object").build())
.build();
Here is following example:
import lombok.Builder;
import lombok.Getter;
import lombok.Singular;
import java.util.List;
@Getter
@Builder
public class GenericsType<T> {
@Singular("entry")
private List<Animal> list;
@Builder
private static class Animal<T> {
T test;
}
public void main(String args[]){
GenericsType.<String>builder()
.entry(Animal.<String>builder().test("my object").build())
.build();
}
}
Is there a way just to pass the generic <String>
one time? Actually the inner class should already know its type.
GenericsType.<String>builder()
.entry(Animal.builder().test("my object").build())
.build();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是 Java 编译器的限制。虽然在这种情况下看起来很明显,类型参数必须是
String
,但推断并不像看起来那么容易:编译器必须通过
test("my object")
将类型信息从build()
向后传播到builder()
方法。新的编译器版本可能支持此类推断,但至少
javac
11 不支持。That is a limitation of the Java compiler. Although it looks obvious in this case that the type parameter must be
String
, inferring that is not as easy as it seems to be:The compiler has to propagate the type information backwards from
build()
viatest("my object")
to thebuilder()
method.New compiler versions may support such inference, but at least
javac
11 does not.