I'm currently learning Groovy and I got stuck with generic methods.
I'd like to define generic method with generic return type that is inferred from argument type.
In Java the signature would be:
<T> T getBean(String name, Class<T> requiredType);
How can I achieve it in Groovy?
Static and non-static generic methods are allowed, as well as generic class constructors. The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type.
From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.
Generic MethodsAll generic method declarations have a type parameter section delimited by angle brackets (< and >) that precedes the method's return type ( < E > in the next example). Each type parameter section contains one or more type parameters separated by commas.
Which of these is an correct way of defining generic method? Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type.
This works in Groovy 2.2.1:
class MyCollection {
def map
public <T> void setMap(Map<String,T> map) {
this.map = map
}
public <T> T getBean(String name, Class<T> requiredType) {
return map.get(name)
}
}
def myc = new MyCollection()
Map<String,Integer> myMap = new HashMap<String,Integer>()
myMap.put("abc",123)
myMap.put("ijk",456)
myc.setMap(myMap)
assert 123 == myc.getBean("abc", Integer.class)
assert 456 == myc.getBean("ijk", Integer.class)
Note that the method is public. If the method is written as "package protected", it won't compile for me.
However, this edit works for package scope:
import groovy.transform.PackageScope
class MyCollection {
// snip
@PackageScope <T> T getBean(String name, Class<T> requiredType) {
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With