什么是静态导入?
静态导入允许我们在代码中直接使用静态成员(方法或字段),而无需通过类名限定,一定是静态方法
import static package.ClassName.staticMember; // 导入单个静态成员
import static package.ClassName.*; // 导入所有静态成员
import static net.commonCommonResult.success;
@PostMapping("/create")
@Operation(summary = "创建物品信息")
public CommonResult<Long> createMaterial(@Valid @RequestBody MaterialSaveReqVO createReqVO) {
return success(materialService.createMaterial(createReqVO));
}
如上述代码使用静态导入后就无需使用 类名.方法 的格式了
// 没有静态导入
CommonResult.success(data);
// 使用静态导入后
success(data); // 等价于 CommonResult.success(data)
对于编译器来说,会判断是否是静态导入,是的话会解析为全限定类名+方法
// 源代码
return success(data);
// 编译后等价于
return CommonResult.success(data);