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

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

问题描述

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

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

class Clazz<T> {
  static void doIt(T object) {
    // ...
  }
}

但是我明白了

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天全站免登陆