Java:如何为“T”设置默认值在SomeClass< T>中 [英] Java: How to set a default for "T" in SomeClass<T>?
问题描述
是否有一种方法可以为通用模板指定默认类型?
假设我有一个 Monkey
类。猴子可以住在不同的 Environment
s,例如 Jungle
或 Zoo
:
公共类Monkey< T扩展环境>
{
T家;
...
public T getHome()
{
return home;
有没有一种方法可以指定
T
,所以我可以使用类型
Monkey
而不是Monkey <?>
而不用编译器警告?
编辑
换句话说,有没有办法得到摆脱原始类型的警告,而不必明确禁止它?
解决方案不,你不能这样做。通用参数没有默认值。您可以重新组织您的类型层次结构,以便有GenericMonkey和DefaultMonkey将泛型参数设置为您所需的默认值。
Is there a way to specify a default type for a generic template?
Let's say I have a
Monkey
class. Monkeys can live in differentEnvironment
s, such asJungle
orZoo
:public class Monkey<T extends Environment> { T home; ... public T getHome() { return home; } }Is there a way to specify a default for
T
, so I can use the typeMonkey
instead ofMonkey<?>
without getting a compiler warning?EDIT
In other words, is there a way to get rid of the "raw type" warning without having to explicitly suppress it?
解决方案No, you can't do that. Generic parameters don't have default values. You could re-organize your type hierarchy so that there's a GenericMonkey and a DefaultMonkey that sets the generic parameter to your desired default.
这篇关于Java:如何为“T”设置默认值在SomeClass< T>中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!