java核心技术 卷1里面泛型一章中“泛型类的静态上下文中类型变量无效”这一节不能理解
ringa_lee
ringa_lee 2017-04-17 17:09:31
0
4
929

书里面这么写的:

public class Singleton<T>
{
    private static T singleInstance    //ERROR
    private static T getSingleInstance()    //ERROR
    {
        if(singleInstance == null)
            return singleInstance;
    }
}

类型擦除后,只剩下Singleton类,它只包含一个singleInstance域。因此,禁止使用带有类型变量的静态域和方法。

不太理解什么意思,为什么跟类型擦除有关系?请高手指点一下

ringa_lee
ringa_lee

ringa_lee

reply all(4)
阿神

First think about how you want to use this method, I think it should be like this:

AType a = Singleton.getSingleInstance();AType a = Singleton.getSingleInstance();

问题来了,上面的getSingleInstance如何知道应该返回什么类型呢?所以这种用法是不允许的。

反过来,如果singleInstancegetSingleInstance

The question is, how does the above getSingleInstance know what type it should return? So this usage is not allowed. 🎜 🎜On the other hand, if singleInstance and getSingleInstance are not static, but instance variables and methods, there will be no problem, because at this time it is clear what type needs to be returned: 🎜
Singleton<AType> s = new Singleton<AType>();
AType a = s.getSingleInstance();
大家讲道理

Generics can only be used by class objects. They are declared and initialized through <>. Different objects have different generic parameters, and class member variables belong to all objects. Therefore, generic class member variables are not allowed to be declared (my own point). Thoughts, just finished reading this part of tij)

小葫芦

After type erasure, the generic type will be replaced by a specific class, usually Object, so if errors are not considered, your class will be

after erasure
public class Singleton
{
    private static Object singleInstance
    private static Object getSingleInstance()
    {
        if(singleInstance == null)
            return singleInstance;
    }
}

Statement when calling

AType a = Singleton.getSingleInstance();

It is equivalent to assigning the Object object to a. This is not allowed and requires forced conversion

This is the same as what "Code Universe" said. getSingleInstance does not know what type it should return. It can only be confirmed at runtime, so this way of writing is problematic.

小葫芦

Because all generic classes are ultimately mapped to the same primitive type class, and static properties are at the class level, the class and the instance share its storage, so one storage cannot accommodate multiple types of properties. The same goes for static methods.

For details, please refer to Java Generics: Type Erasure

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template