首页 > 解决方案 > 为什么受保护的构造函数可以用于包外的新实例?

问题描述

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

标签: javagson

解决方案


您看到的是匿名类的语法:

基本上发生的事情是,

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

定义了一个新的匿名类,它继承自TypeToken. 您可以立即从new结合花括号的语法中得出这一点{}

允许您访问protected构造函数的原因是因为protected允许访问包继承类。由于您的匿名类从TypeToken访问继承是可能的。


推荐阅读