[英]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' '非静态方法generateMatches(org.jdom.Document)
无法从静态上下文中引用'
Turned comment into answer: 将评论转变为答案:
You can introduce an instance variable of type T and call generateMatches on that. 您可以引入类型为T的实例变量,并在其上调用generateMatches。 You cannot call generateMatches on the type T itself. 您不能在类型T本身上调用generateMatches。
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: 在getMatches方法中,您可以执行以下操作:
return instanceOfT.generateMatches(doc);
Your problem is that you do not have handle to any object of class T
. 您的问题是您没有T
类任何对象的句柄。 Just saying T.generateMatches(doc)
means you are making a static call to static method in class T
. 只是说T.generateMatches(doc)
意味着你正在对T
类中的静态方法进行静态调用。 You need to have a variable of type T
to call instance methods. 您需要有一个类型为T
的变量来调用实例方法。
What's the question ? 问题是什么 ?
The reason is clear - the line "T.generateMatches(doc);" 原因很清楚 - “T.generateMatches(doc);” calls generateMatches through T, and T is type (class/interface), not instance. 通过T调用generateMatches,T是类型(类/接口),而不是实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.