Java Generic Static Function

Hey, I'm trying to write a function that calls a static function based on its general arguments. I have 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 to do this, I just get something about static contexts. "the non-static generateMatches(org.jdom.Document) method generateMatches(org.jdom.Document) cannot refer to a static context"

+4
source share
3 answers

Turned a comment in response:

You can enter an instance variable of type T and call generateMatches. You cannot call generateMatches on type T.

You can, for example, insert this instance variable through the constructor and save it in a private variable:

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

In your getMatches method, you can do this:

 return instanceOfT.generateMatches(doc); 
+4
source

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

+2
source

What question?

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

0
source

Source: https://habr.com/ru/post/1342258/


All Articles