为什么受保护的构造函数可以用于包外的新实例?
来自 gson-2.8.6.jar
package com.google.gson.reflect;
...
public class TypeToken<T> {
final Class<? super T> rawType;
final Type type;
final int hashCode;
/**
* Constructs a new type literal. Derives represented class from type
* parameter.
*
* <p>Clients create an empty anonymous subclass. Doing so embeds the type
* parameter in the anonymous class's type hierarchy so we can reconstitute it
* at runtime despite erasure.
*/
@SuppressWarnings("unchecked")
protected TypeToken() {
this.type = getSuperclassTypeParameter(getClass());
this.rawType = (Class<? super T>) $Gson$Types.getRawType(type);
this.hashCode = type.hashCode();
}
/**
* Unsafe. Constructs a type literal manually.
*/
@SuppressWarnings("unchecked")
TypeToken(Type type) {
this.type = $Gson$Types.canonicalize($Gson$Preconditions.checkNotNull(type));
this.rawType = (Class<? super T>) $Gson$Types.getRawType(this.type);
this.hashCode = this.type.hashCode();
}
...
}
在包之外com.google.gson.reflect,为什么protected TypeToken()构造函数可以用来新建一个实例?后面出现
的语法是什么?{}new TypeToken<String>()
package com.dataservice.controller;
...
Type localVarReturnType = (new TypeToken<String>() {}).getType();
...
回答
您看到的是匿名类的语法:
- https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
基本上发生的事情是,
Type localVarReturnType = (new TypeToken<String>() {}).getType();
定义了一个新的匿名类,它继承自TypeToken. 您可以立即从new结合花括号的语法中得出这一点{}。
之所以允许您访问protected构造函数,是因为protected允许访问包或继承类。由于您的匿名类继承自TypeTokenaccess 是可能的。