Java static function on generics

2019-06-24 09:45发布

问题:

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'

回答1:

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);


回答2:

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.



回答3:

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.