Skeen
Skeen

Reputation: 4732

Java static function on generics

Hey I'm trying to write a function that calls a static function based upon its generic arguments. I'm having the following code:

public class Model<T extends Listable>
{
    private Document doc;

    /*
        When the JavaBean is created, a Document object is made using
        the Listable parameter. The request string for the specific
        type is used to pull XML-data from the cloud.
    */
    public Model()
    {
        try
        {
            doc = cloud.request(T.getRequestString());
        }
        catch(Exception e)
        {
        }
    }

    /*
        getMatches (used in JSP as "foo.matches") generates a list
        of objects implementing the Listable interface.
    */
    public List<Listable> getMatches()
    {
        return T.generateMatches(doc);
    }
}

How do I do this, I'm just getting something about static contexts. 'non-static method generateMatches(org.jdom.Document) cannot be referenced from a static context'

Upvotes: 4

Views: 596

Answers (3)

Zds
Zds

Reputation: 4359

Your problem is that you do not have handle to any object of class T. Just saying T.generateMatches(doc) means you are making a static call to static method in class T. You need to have a variable of type T to call instance methods.

Upvotes: 2

Eric Eijkelenboom
Eric Eijkelenboom

Reputation: 7021

Turned comment into answer:

You can introduce an instance variable of type T and call generateMatches on that. You cannot call generateMatches on the type T itself.

You could e.g. inject this instance variable via the constructor and store it in a private variable:

private T instanceOfT;

public Model(T instanceOfT){
    this.instanceOfT= instanceOfT;
}

In your getMatches method you can then do this:

return instanceOfT.generateMatches(doc);

Upvotes: 4

Rostislav Matl
Rostislav Matl

Reputation: 4553

What's the question ?

The reason is clear - the line "T.generateMatches(doc);" calls generateMatches through T, and T is type (class/interface), not instance.

Upvotes: 0

Related Questions