泛型类中的静态方法? [英] Static method in a generic class?

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

问题描述

在Java中,我想要有一些东西:

  class Clazz< T> {
static void doIt(T object){
// shake the booty
}
}

但是我得到了

无法对非静态类型T  

我不理解基本用法之外的泛型,因此无法理解这一点。这无助于我无法在互联网上找到有关该主题的更多信息。



有人能否通过类似的方式澄清这种使用是否可能?此外,为什么我的原始尝试失败?

解决方案

不能在静态方法或静态字段中使用类的泛型类型参数。类的类型参数仅在实例方法和实例字段的范围内。对于静态字段和静态方法,它们在类的所有实例之间共享,即使是不同类型参数的实例,显然它们不能依赖于特定的类型参数。



看起来你的问题似乎并不需要使用类的类型参数。如果您更详细地描述了您正在尝试做的事情,也许我们可以帮助您找到更好的方法。


In Java, I'd like to have something as:

class Clazz<T> {
  static void doIt(T object) {
    // shake that booty
  }
}

But I get

Cannot make a static reference to the non-static type T

I don't understand generics beyond the basic uses and thus can't make much sense of that. It doesn't help that I wasn't able to find much info on the internet about the subject.

Could someone clarify if such use is possible, by a similar manner? Also, why was my original attempt unsuccessful?

解决方案

You can't use a class's generic type parameters in static methods or static fields. The class's type parameters are only in scope for instance methods and instance fields. For static fields and static methods, they are shared among all instances of the class, even instances of different type parameters, so obviously they cannot depend on a particular type parameter.

It doesn't seem like your problem should require using the class's type parameter. If you describe what you are trying to do in more detail, maybe we can help you find a better way to do it.

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

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