简体   繁体   中英

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'

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM