Java:如何为“T”设置默认值在SomeClass< T>中 [英] Java: How to set a default for "T" in SomeClass<T>?

查看:95
本文介绍了Java:如何为“T”设置默认值在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 different Environments, such as Jungle or Zoo:

    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 type Monkey instead of Monkey<?> 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&lt; T&gt;中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆