2012-01-06 153 views
0

还有就是generics here泛型类型类defition

一个很好的讨论,但是他们都谈阶级如何接受泛型类型变量。我的问题是在泛型类定义上。

的类定义为

protected final <T> T getBeanFromSpringContext(String name, Class<T> requiredType) { 
    if(springApplicationContext != null) { 
     return springApplicationContext.getBean(name, requiredType); 
    } else { 
     return null; 
    } 
} 

现在我明白了,返回类型为T。但在此之前<T>是由此Class对象建模的类的类型。为什么这不是<?>,因为我不知道类型?

而且自返回类型是T。如上所述,这个班级能否返回null

+1

顺便说一句,我喜欢这种单线条样式:'回报springApplicationContext == NULL? null:springApplicationContext.getBean(name,requiredType);' – Bohemian 2012-01-06 10:37:53

回答

2

<T>之前的声明说,该方法是通用的,它有一个类型参数T - 也就是说,它是一个definition of a type variable

这可能是一个有点不同:

protected final <T extends Collection> T getBeanFromSpringContext(String name, Class<T> requiredType) { 
    if(springApplicationContext != null) { 
     return springApplicationContext.getBean(name, requiredType); 
    } else { 
     return null; 
    } 
} 

不仅会说你有一个类型参数,而且还会把一些制约因素,“界限”,在它的值。

更新:现在,在null部分。不幸的是,所有非原始类型都是Java中的“这种类型或null”。所以是的,你总是可以返回null。你总是可以得到一个NPE。

An obligatory Angelika Langer's FAQ link