this key -- think in java notes

本文探讨了Java中使用'this'关键字在类间传递对象以调用外部工具方法,如削皮器类(Peeler)来处理苹果(Apple)对象的特定操作。通过实例展示了如何在不修改类内部结构的情况下,实现对象间的协作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

this 关键字对于将当前对象传递给其他方法很有用
class Person{
	public void eat(Apple apple){
		Apple peeled = apple.getPeeled();  //apple.getPeeled() == Peeler.peel(apple) == apple
		System.out.println("Yummy");
	}
}

class Peeler{                               //削皮
	static Apple peel(Apple apple){
		return apple;
	}
}

class Apple{
	Apple getPeeled() { return Peeler.peel(this);}
}

public class TJ_5_41 {
	public static void main(String[] args){
		new Person().eat(new Apple());
	}
}
apple需要调用Peeler.peel()方法,他是一个外部工具方法,将执行由于某种原因必须放在Apple外部的操作.
package com.zzyl.nursing.controller; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.zzyl.common.core.domain.R; import com.zzyl.nursing.vo.NursingProjectVo; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.zzyl.common.annotation.Log; import com.zzyl.common.core.controller.BaseController; import com.zzyl.common.core.domain.AjaxResult; import com.zzyl.common.enums.BusinessType; import com.zzyl.nursing.domain.NursingProject; import com.zzyl.nursing.service.INursingProjectService; import com.zzyl.common.utils.poi.ExcelUtil; import com.zzyl.common.core.page.TableDataInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiImplicitParam; /** * 护理项目Controller * * @author ruoyi * @date 2025-08-07 */ @RestController @RequestMapping("/nursing/project") @Api(tags = "护理项目管理", description = "护理项目相关的操作接口") public class NursingProjectController extends BaseController { @Autowired private INursingProjectService nursingProjectService; /** * 获取所有护理计划 * @return */ @GetMapping("/all") @ApiOperation("获取所有护理计划") public AjaxResult all() { List<NursingProjectVo> list = nursingProjectService.listAll(); return success(list); } /** * 查询护理项目列表 */ @PreAuthorize("@ss.hasPermi('nursing:project:list')") @GetMapping("/list") @ApiOperation(value = "查询护理项目列表", notes = "根据条件查询护理项目列表信息") public TableDataInfo<List<NursingProject>> list( @ApiParam(name = "nursingProject", value = "护理项目查询条件", required = false) NursingProject nursingProject) { startPage(); List<NursingProject> list = nursingProjectService.selectNursingProjectList(nursingProject); return getDataTable(list); } /** * 导出护理项目列表 */ @PreAuthorize("@ss.hasPermi('nursing:project:export')") @Log(title = "护理项目", businessType = BusinessType.EXPORT) @PostMapping("/export") @ApiOperation(value = "导出护理项目列表", notes = "将护理项目数据导出为Excel文件") public void export( @ApiParam(name = "response", value = "HttpServletResponse对象", required = true) HttpServletResponse response, @ApiParam(name = "nursingProject", value = "护理项目查询条件", required = false) NursingProject nursingProject) { List<NursingProject> list = nursingProjectService.selectNursingProjectList(nursingProject); ExcelUtil<NursingProject> util = new ExcelUtil<NursingProject>(NursingProject.class); util.exportExcel(response, list, "护理项目数据"); } /** * 获取护理项目详细信息 */ @PreAuthorize("@ss.hasPermi('nursing:project:query')") @GetMapping(value = "/{id}") @ApiOperation(value = "获取护理项目详情", notes = "根据ID获取护理项目的详细信息") @ApiImplicitParam(name = "id", value = "护理项目ID", required = true, dataType = "Long", paramType = "path") public R<NursingProject> getInfo( @ApiParam(name = "id", value = "护理项目ID", required = true) @PathVariable("id") Long id) { return R.ok(nursingProjectService.selectNursingProjectById(id)); } /** * 新增护理项目 */ @PreAuthorize("@ss.hasPermi('nursing:project:add')") @Log(title = "护理项目", businessType = BusinessType.INSERT) @PostMapping @ApiOperation(value = "新增护理项目", notes = "添加一个新的护理项目信息") public AjaxResult add( @ApiParam(name = "nursingProject", value = "护理项目信息", required = true) @RequestBody NursingProject nursingProject) { return toAjax(nursingProjectService.insertNursingProject(nursingProject)); } /** * 修改护理项目 */ @PreAuthorize("@ss.hasPermi('nursing:project:edit')") @Log(title = "护理项目", businessType = BusinessType.UPDATE) @PutMapping @ApiOperation(value = "修改护理项目", notes = "更新已有的护理项目信息") public AjaxResult edit( @ApiParam(name = "nursingProject", value = "护理项目信息", required = true) @RequestBody NursingProject nursingProject) { return toAjax(nursingProjectService.updateNursingProject(nursingProject)); } /** * 删除护理项目 */ @PreAuthorize("@ss.hasPermi('nursing:project:remove')") @Log(title = "护理项目", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") @ApiOperation(value = "删除护理项目", notes = "根据ID批量删除护理项目信息") @ApiImplicitParam(name = "ids", value = "护理项目ID数组", required = true, dataType = "Long[]", paramType = "path") public AjaxResult remove( @ApiParam(name = "ids", value = "护理项目ID数组", required = true) @PathVariable Long[] ids) { return toAjax(nursingProjectService.deleteNursingProjectByIds(ids)); } } package com.zzyl.nursing.domain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.zzyl.common.annotation.Excel; import com.zzyl.common.core.domain.BaseEntity; /** * 护理项目对象 nursing_project * * @author ruoyi * @date 2025-08-07 */ @ApiModel(description = "护理项目实体") public class NursingProject extends BaseEntity { private static final long serialVersionUID = 1L; /** 编号 */ @ApiModelProperty(value = "编号") private Long id; /** 名称 */ @Excel(name = "名称") @ApiModelProperty(value = "名称") private String name; /** 排序号 */ @Excel(name = "排序号") @ApiModelProperty(value = "排序号") private Integer orderNo; /** 单位 */ @Excel(name = "单位") @ApiModelProperty(value = "单位") private String unit; /** 价格 */ @Excel(name = "价格") @ApiModelProperty(value = "价格") private Double price; /** 图片 */ @Excel(name = "图片") @ApiModelProperty(value = "图片URL") private String image; /** 护理要求 */ @Excel(name = "护理要求") @ApiModelProperty(value = "护理要求") private String nursingRequirement; /** 状态(0:禁用,1:启用) */ @Excel(name = "状态", readConverterExp = "0=:禁用,1:启用") @ApiModelProperty(value = "状态(0:禁用,1:启用)") private Integer status; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setOrderNo(Integer orderNo) { this.orderNo = orderNo; } public Integer getOrderNo() { return orderNo; } public void setUnit(String unit) { this.unit = unit; } public String getUnit() { return unit; } public void setPrice(Double price) { this.price = price; } public Double getPrice() { return price; } public void setImage(String image) { this.image = image; } public String getImage() { return image; } public void setNursingRequirement(String nursingRequirement) { this.nursingRequirement = nursingRequirement; } public String getNursingRequirement() { return nursingRequirement; } public void setStatus(Integer status) { this.status = status; } public Integer getStatus() { return status; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("name", getName()) .append("orderNo", getOrderNo()) .append("unit", getUnit()) .append("price", getPrice()) .append("image", getImage()) .append("nursingRequirement", getNursingRequirement()) .append("status", getStatus()) .append("createBy", getCreateBy()) .append("updateBy", getUpdateBy()) .append("remark", getRemark()) .append("createTime", getCreateTime()) .append("updateTime", getUpdateTime()) .toString(); } } package com.zzyl.plan.controller; import java.util.List; import javax.servlet.http.HttpServletResponse; import com.zzyl.nursing.dto.NursingPlanDto; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.zzyl.common.annotation.Log; import com.zzyl.common.core.controller.BaseController; import com.zzyl.common.core.domain.AjaxResult; import com.zzyl.common.enums.BusinessType; import com.zzyl.plan.domain.NursingPlan; import com.zzyl.plan.service.INursingPlanService; import com.zzyl.common.utils.poi.ExcelUtil; import com.zzyl.common.core.page.TableDataInfo; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; /** * 护理计划Controller * * @author ruoyi * @date 2025-08-07 */ @Api(tags = "护理计划管理") @RestController @RequestMapping("/nursing/plan") public class NursingPlanController extends BaseController { @Autowired private INursingPlanService nursingPlanService; /** * 查询护理计划列表 */ @ApiOperation("查询护理计划列表") @PreAuthorize("@ss.hasPermi('nursing:plan:list')") @GetMapping("/list") public TableDataInfo list( @ApiParam("护理计划查询参数") NursingPlan nursingPlan) { startPage(); List<NursingPlan> list = nursingPlanService.selectNursingPlanList(nursingPlan); return getDataTable(list); } /** * 导出护理计划列表 */ @ApiOperation("导出护理计划列表") @PreAuthorize("@ss.hasPermi('nursing:plan:export')") @Log(title = "护理计划", businessType = BusinessType.EXPORT) @PostMapping("/export") public void export( @ApiParam("HTTP响应对象") HttpServletResponse response, @ApiParam("护理计划查询参数") NursingPlan nursingPlan) { List<NursingPlan> list = nursingPlanService.selectNursingPlanList(nursingPlan); ExcelUtil<NursingPlan> util = new ExcelUtil<NursingPlan>(NursingPlan.class); util.exportExcel(response, list, "护理计划数据"); } /** * 获取护理计划详细信息 */ @ApiOperation("获取护理计划详细信息") @PreAuthorize("@ss.hasPermi('nursing:plan:query')") @GetMapping(value = "/{id}") public AjaxResult getInfo( @ApiParam("护理计划ID") @PathVariable("id") Long id) { return success(nursingPlanService.selectNursingPlanById(id)); } /** * 新增护理计划 */ @ApiOperation("新增护理计划") @PreAuthorize("@ss.hasPermi('nursing:plan:add')") @Log(title = "护理计划", businessType = BusinessType.INSERT) @PostMapping public AjaxResult add( @ApiParam("护理计划对象") @RequestBody NursingPlanDto dto) { return toAjax(nursingPlanService.insertNursingPlan(dto)); } /** * 修改护理计划 */ @ApiOperation("修改护理计划") @PreAuthorize("@ss.hasPermi('nursing:plan:edit')") @Log(title = "护理计划", businessType = BusinessType.UPDATE) @PutMapping public AjaxResult edit( @ApiParam("护理计划对象") @RequestBody NursingPlan nursingPlan) { return toAjax(nursingPlanService.updateNursingPlan(nursingPlan)); } /** * 删除护理计划 */ @ApiOperation("删除护理计划") @PreAuthorize("@ss.hasPermi('nursing:plan:remove')") @Log(title = "护理计划", businessType = BusinessType.DELETE) @DeleteMapping("/{ids}") public AjaxResult remove( @ApiParam("护理计划ID数组") @PathVariable Long[] ids) { return toAjax(nursingPlanService.deleteNursingPlanByIds(ids)); } } <template> <div class="app-container"> <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px"> <el-form-item label="护理项目名称" prop="name"> <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" /> </el-form-item> <el-form-item label="状态" prop="status"> <el-select v-model="queryParams.status" placeholder="请选择" clearable> <el-option v-for="item in nursing_project_status" :key="item.value" :label="item.label" :value="item.value" /> </el-select> </el-form-item> <el-form-item> <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button> <el-button icon="Refresh" @click="resetQuery">重置</el-button> </el-form-item> </el-form> <el-row :gutter="10" class="mb8"> <el-col :span="1.5"> <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['nursing:project:add']" >新增</el-button> </el-col> <!-- <el-col :span="1.5"> <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate" v-hasPermi="['nursing:project:edit']" >修改</el-button> </el-col> --> <!-- <el-col :span="1.5"> <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['nursing:project:remove']" >删除</el-button> </el-col> --> <!-- <el-col :span="1.5"> <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['nursing:project:export']" >导出</el-button> </el-col> --> <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> </el-row> <el-table v-loading="loading" :data="projectList" @selection-change="handleSelectionChange"> <el-table-column type="selection" width="55" align="center" /> <!-- 调整列顺序 --> <el-table-column label="序号" align="center" type="index" width="70" /> <el-table-column label="护理图片" align="center" prop="image" width="100"> <template #default="scope"> <image-preview :src="scope.row.image" :width="50" :height="50"/> </template> </el-table-column> <el-table-column label="护理项目名称" align="center" prop="name" /> <el-table-column label="价格(元)" align="center" prop="price" /> <el-table-column label="单位" align="center" prop="unit" /> <el-table-column label="排序" align="center" prop="orderNo" /> <el-table-column label="创建人" align="center" prop="createBy" /> <el-table-column label="创建时间" align="center" prop="createTime" width="180" /> <el-table-column label="状态" align="center" prop="status"> <template #default="scope"> <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">{{ scope.row.status === 1 ? '启用' : '禁用' }}</el-tag> </template> </el-table-column> <el-table-column label="操作" width="200" fixed="right" align="center" class-name="small-padding fixed-width"> <template #default="scope"> <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['nursing:project:edit']">修改</el-button> <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['nursing:project:remove']">删除</el-button> <!-- 新增一个修改状态禁用操作 --> <el-button link type="primary" :icon="scope.row.status == 0 ? 'Lock' : 'Unlock'" @click="handleEnable(scope.row)" >{{ scope.row.status === 1 ? '禁用' : '启用' }}</el-button> </template> </el-table-column> </el-table> <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" /> <!-- 添加或修改护理项目对话框 --> <el-dialog :title="title" v-model="open" width="500px" append-to-body> <el-form ref="projectRef" :model="form" :rules="rules" label-width="120px"> <el-form-item label="护理项目名称" prop="name"> <el-input v-model="form.name" placeholder="请输入名称" :maxlength="10" show-word-limit /> </el-form-item> <el-form-item label="价格" prop="price"> <el-input v-model="form.price" placeholder="请输入价格" @input="validatePrice" /> </el-form-item> <el-form-item label="单位" prop="unit"> <el-input v-model="form.unit" placeholder="请输入单位" :maxlength="5" show-word-limit /> </el-form-item> <el-form-item label="排序号" prop="orderNo"> <el-input-number v-model="form.orderNo" placeholder="请输入" :min="1" :max="999999" controls-position="right" /> </el-form-item> <el-form-item label="状态" prop="status"> <el-radio-group v-model="form.status"> <el-radio v-for="dict in nursing_project_status" :key="dict.value" :label="dict.value" > {{ dict.label }} </el-radio> </el-radio-group> </el-form-item> <el-form-item label="图片" prop="image"> <image-upload v-model="form.image"/> </el-form-item> <el-form-item label="护理要求" prop="nursingRequirement"> <el-input v-model="form.nursingRequirement" placeholder="请输入护理要求" type="textarea" :maxlength="50" show-word-limit :autosize="{ minRows: 2, maxRows: 4 }" /> </el-form-item> </el-form> <template #footer> <div class="dialog-footer"> <el-button type="primary" @click="submitForm">确 定</el-button> <el-button @click="cancel">取 消</el-button> </div> </template> </el-dialog> </div> </template> <script setup name="Project"> import { listProject, getProject, delProject, addProject, updateProject } from "@/api/nursing/project"; import { ref } from "vue"; const { proxy } = getCurrentInstance(); const projectList = ref([]); const open = ref(false); const loading = ref(true); const showSearch = ref(true); const ids = ref([]); const single = ref(true); const multiple = ref(true); const total = ref(0); const title = ref(""); //引用数据字典 const dictResult = proxy.useDict("nursing_project_status"); const nursing_project_status = dictResult?.nursing_project_status || []; /* const options = ref([ { value: 1, label: "启用" }, { value: 0, label: "禁用" } ]); */ //禁用或启用 const handleEnable = (row) => { // 获取状态 const status = row.status === 1 ? 0 : 1; //弹窗提示,并发送请求 proxy.$modal.confirm('确认要' + (status === 1 ? "启用" : "禁用") + row.name + '护理项目吗?').then(function () { return updateProject({ id: row.id, status: status }); }).then(() => { proxy.$modal.msgSuccess(status === 1 ? "启用成功" : "禁用成功"); getList(); }).catch(function () { row.status = row.status === 1 ? 0 : 1; }) } /** * 价格输入验证 * @description 限制价格输入格式,只允许数字和小数点,最多两位小数 */ function validatePrice(value) { // 保留两位小数 let price = value.toString(); if (price.includes('.')) { const parts = price.split('.'); if (parts[1].length > 2) { form.value.price = parts[0] + '.' + parts[1].substring(0, 2); } } } const data = reactive({ form: {}, queryParams: { pageNum: 1, pageSize: 10, name: null, status: null, }, rules: { name: [ { required: true, message: "护理项目名称不能为空", trigger: "blur" }, { min: 1, max: 10, message: "护理项目名称长度不能超过10个字符", trigger: "blur" } ], price: [ { required: true, message: "价格不能为空", trigger: "blur" }, { pattern: /^([0-9]\d*|0)(\.\d{1,2})?$/, message: "请输入正确的金额格式,最多两位小数", trigger: "blur" } ], unit: [ { required: true, message: "单位不能为空", trigger: "blur" }, { min: 1, max: 5, message: "单位长度不能超过5个字符", trigger: "blur" } ], orderNo: [ { required: true, message: "排序号不能为空", trigger: "blur" }, { type: "number", message: "排序号必须为数字值", trigger: "blur" } ], status: [ { required: true, message: "状态不能为空", trigger: "change" } ], image: [ { required: true, message: "图片不能为空", trigger: "change" } ], nursingRequirement: [ { required: true, message: "护理要求不能为空", trigger: "blur" }, { min: 1, max: 50, message: "护理要求长度不能超过50个字符", trigger: "blur" } ] } }); const { queryParams, form, rules } = toRefs(data); /** * 查询护理项目列表 * @description 获取护理项目数据并更新到页面中 */ function getList() { loading.value = true; listProject(queryParams.value).then(response => { projectList.value = response.rows; total.value = response.total; loading.value = false; }); } /** * 取消按钮操作 * @description 关闭弹窗并重置表单 */ function cancel() { open.value = false; reset(); } /** * 表单重置 * @description 将表单数据恢复为初始状态,并清空校验结果 */ function reset() { form.value = { id: null, name: null, orderNo: 1, unit: null, price: null, image: null, nursingRequirement: null, status: 1, // 默认启用状态 createBy: null, updateBy: null, remark: null, createTime: null, updateTime: null }; proxy.resetForm("projectRef"); } /** * 搜索按钮操作 * @description 触发查询操作,将页码重置为第一页 */ function handleQuery() { queryParams.value.pageNum = 1; getList(); } /** * 重置按钮操作 * @description 重置搜索条件并重新加载数据 */ function resetQuery() { proxy.resetForm("queryRef"); handleQuery(); } /** * 多选框选中数据处理 * @param {Array} selection - 当前选中的行数据数组 * @description 更新选中项ID列表,并控制修改/删除按钮的可用性 */ function handleSelectionChange(selection) { ids.value = selection.map(item => item.id); single.value = selection.length != 1; multiple.value = !selection.length; } /** * 新增按钮操作 * @description 打开新增护理项目的弹窗 */ function handleAdd() { reset(); open.value = true; title.value = "添加护理项目"; } /** * 修改按钮操作 * @param {Object} row - 要修改的数据行对象(可选) * @description 根据传入的行数据或选中ID获取详细信息并打开编辑弹窗 */ function handleUpdate(row) { reset(); const _id = row.id || ids.value getProject(_id).then(response => { form.value = response.data; open.value = true; title.value = "修改护理项目"; }); } /** * 提交按钮操作 * @description 验证表单并根据是否有ID决定是新增还是修改操作 */ function submitForm() { proxy.$refs["projectRef"].validate(valid => { if (valid) { if (form.value.id != null) { updateProject(form.value).then(response => { proxy.$modal.msgSuccess("修改成功"); open.value = false; getList(); }); } else { addProject(form.value).then(response => { proxy.$modal.msgSuccess("新增成功"); open.value = false; getList(); }); } } }); } /** * 删除按钮操作 * @param {Object} row - 要删除的数据行对象(可选) * @description 删除指定ID的数据项,并提示用户确认操作 */ function handleDelete(row) { const _ids = row.id || ids.value; proxy.$modal.confirm('是否确认删除护理项目编号为"' + _ids + '"的数据项?').then(function() { return delProject(_ids); }).then(() => { getList(); proxy.$modal.msgSuccess("删除成功"); }).catch(() => {}); } /** * 导出按钮操作 * @description 导出当前查询条件下的护理项目数据为Excel文件 */ function handleExport() { proxy.download('nursing/project/export', { ...queryParams.value }, `project_${new Date().getTime()}.xlsx`) } // 初始化加载数据 getList(); </script> 如果该护理项目,已经被护理计划所引用,则不能进行删除、编辑、禁用
08-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值