java - 为什么受保护的构造函数可以用于包外的新实例?
问题描述
来自 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();
...
解决方案
您看到的是匿名类的语法:
基本上发生的事情是,
Type localVarReturnType = (new TypeToken<String>() {}).getType();
定义了一个新的匿名类,它继承自TypeToken
. 您可以立即从new
结合花括号的语法中得出这一点{}
。
允许您访问protected
构造函数的原因是因为protected
允许访问包或继承类。由于您的匿名类从TypeToken
访问继承是可能的。
推荐阅读
- php - 无法访问 Microsoft Dynamics 365 Business Central 的 APIS
- macos - HAL 虚拟设备:如何“代理”麦克风
- python - 山楂到铁木的迁移(Open edX)
- php - 多个查询 mysqli
- java - 如何将 String("dog") 拆分为 Arraylist ['d', 'o', 'g']?
- java - 在 Pentaho 数据集成中打开任何 Kettle 转换文件时出错
- java - 无法成功链接 OpenGL 程序
- class - Kotlin 类中“this”的目的
- android - 从回收者视图适配器中获取价值到活动
- html - 尝试使用 CSS 在其他图像上添加图像