(Java)静态泛型方法与泛型类静态方法 [英] (Java) Static generic methods versus generic class static methods

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

问题描述

我已经阅读了关于为什么在泛型类中不能有(编辑 - 泛型)(它使用泛型类中的类型参数)静态方法的帖子,但是为什么您可以在静态泛型方法中使用静态泛型方法非泛型类?我没有看到第二个被允许的原因,但我有点理解为什么第一个不是。

解决方案


为什么你不能在泛型类中有一个(Edit - generic)(它使用泛型类中的那个类型参数)静态方法

原因很简单:类型参数与关联,但与实例关联

即,你不能做

  class Test< ; T> {
public static void sayHello(T t){// T为哪个实例?!
System.out.println(Hello);
}
}


$ b


为什么你可以在非泛型类中使用静态泛型方法?


你为什么不呢?泛型方法接受类型参数,所以不管它是静态的还是非静态的,或者它所在的类是通用的还是不是等等。

这个例子编译好:

  class Test {
public static< T> void sayHello(T t){
System.out.println(Hello+ t);


你可以这样调用方法:

  Test。< String> sayHello(some argument); 
^^^^^^^^ $方法调用提供的b $ b类型参数:不需要实例。


I've read posts about why you can't have a (Edit -- generic) (which use that type parameter from the generic class) static method in a generic class, but why can you then use static generic methods in non generic classes? I don't see the why the second is allowed, but I kinda understand why the first isn't.

解决方案

why you can't have a (Edit -- generic) (which use that type parameter from the generic class) static method in a generic class

The reason for this is simple: The type parameter is not associated with the class but with instances of the class.

I.e., you can't do

class Test<T> {
    public static void sayHello(T t) {    // T for which instance?!
        System.out.println("Hello");
    }
}


why can you then use static generic methods in non generic classes?

Why wouldn't you? A generic method takes the type parameter, so it doesn't matter if it's static or not, or if the class it's in is generic or not etc.

This for instance compiles fine:

class Test {
    public static <T> void sayHello(T t) {
        System.out.println("Hello " + t);
    }
}

And you'd call the method like this:

Test.<String>sayHello("some argument");
     ^^^^^^^^
     type parameter provided at the method-call: no instance required.

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

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