[英]Java static function on generics
嘿我正在尝试编写一个基于其泛型参数调用静态函数的函数。 我有以下代码:
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);
}
}
我该怎么做,我只是得到一些关于静态上下文的东西。 '非静态方法generateMatches(org.jdom.Document)
无法从静态上下文中引用'
将评论转变为答案:
您可以引入类型为T的实例变量,并在其上调用generateMatches。 您不能在类型T本身上调用generateMatches。
您可以通过构造函数注入此实例变量并将其存储在私有变量中:
private T instanceOfT;
public Model(T instanceOfT){
this.instanceOfT= instanceOfT;
}
在getMatches方法中,您可以执行以下操作:
return instanceOfT.generateMatches(doc);
您的问题是您没有T
类任何对象的句柄。 只是说T.generateMatches(doc)
意味着你正在对T
类中的静态方法进行静态调用。 您需要有一个类型为T
的变量来调用实例方法。
问题是什么 ?
原因很清楚 - “T.generateMatches(doc);” 通过T调用generateMatches,T是类型(类/接口),而不是实例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.