Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method in Groovy [duplicate]

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?

like image 954
Maciej Ziarko Avatar asked Mar 15 '14 18:03

Maciej Ziarko


People also ask

Can generic methods be static?

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.

How does a generic method differ from a generic 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.

How do you declare a generic method How do you invoke a generic method?

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?

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.


1 Answers

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) {
like image 133
Michael Easter Avatar answered Sep 25 '22 01:09

Michael Easter