【问题标题】:Why protected constructor can be used to new instance outside of the package?为什么受保护的构造函数可以用于包外的新实例?
【发布时间】:2021-07-28 11:22:23
【问题描述】:

来自 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&lt;String&gt;()之后的语法是什么?

package com.dataservice.controller;

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

【问题讨论】:

  • this 回答你的问题了吗?

标签: java gson


【解决方案1】:

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

基本上发生的事情是,

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

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

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

【讨论】:

    猜你喜欢
    • 2010-11-06
    • 2015-06-14
    • 1970-01-01
    • 2013-10-06
    • 2013-08-04
    • 1970-01-01
    • 2012-04-23
    • 2014-04-22
    • 2016-01-26
    相关资源
    最近更新 更多