为什么受保护的构造函数可以用于包外的新实例?

Why protected constructor can be used to new instance outside of the package?

来自 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();
...

您看到的是匿名 class:

的语法

基本上发生的事情是,

Type localVarReturnType = (new TypeToken<String>() {}).getType();

定义了一个继承自TypeToken的新匿名class。您可以立即从语法 new 结合大括号 {}.

中得出这一点

之所以允许您访问 protected 构造函数,是因为 protected 允许访问包 以继承 class是的。由于您的匿名 class 继承自 TypeToken,因此访问是可能的。