泛型上的Java静态函数 [英] Java static function on generics

查看:81
本文介绍了泛型上的Java静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嘿,我试图编写一个函数,它根据泛型参数调用一个静态函数。
我有以下代码:

  public class Model< T extends Listable> 
{
私人文档文档;

/ *
创建JavaBean时,Document对象使用
Listable参数创建。特定
类型的请求字符串用于从云中提取XML数据。
* /
public Model()
{
try
{
doc = cloud.request(T.getRequestString());
}
catch(Exception e)
{
}
}
$ b $ * / $
getMatches(在JSP中用作 foo.matches)生成一个实现Listable接口的对象列表

* /
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;

$ / code>

在getMatches方法中,您可以执行此操作:

  return instanceOfT.generateMatches(doc); 


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

这篇关于泛型上的Java静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆