gpt4 book ai didi

按参数类型转换的 Java 泛型

转载 作者:搜寻专家 更新时间:2023-11-01 02:33:39 25 4
gpt4 key购买 nike

如果可能的话,什么是一个很好的解决方案来实现我想要的以下所需功能:

  • 将例程的返回类型转换为例程参数的类型,例如,

// Foo and Bar are two types of Common
interface Common{}
interface Foo extends Common {}
interface Bar extends Common {}

// Example interface
public List<? extends Common> getFeatureByType(Class<? extends Common> clazz);


// Example of what I want to achieve by using the (or a similar) interface.
// Can this be achieve without using typecasting to (List<Bar>) or (List<Foo>)
// and @SuppressWarning("unchecked") ?
List<Bar> bars = getFeatureByType(Bar.class);
List<Foo> foos = getFeatureByType(Foo.class);

最佳答案

public <T extends Common> List<T> getFeatureByType(Class<T> clazz);

关于按参数类型转换的 Java 泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3440187/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com