4

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'

3 Answers 3

4

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Accepted the best, but unacceptable solution. - Changed to C++
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.

Comments

0

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.

4 Comments

Right, well how should I make my above code work, I guess thats the question
Introduce an instance variable of type T and call generateMatches on that, not on the type T.
@Eric you are the first person making sense on this page. Why not add this as an answer?
Either make both doc and getMatches() static (and set doc using some static method, of course) or go the way Eric suggested. Depends on your needs - Eric's solution looks better for you code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.