生成对String 进行自动trim()的setter

本文介绍了如何在IDEA中创建代码模板,使得在生成setter方法时,对于String类型的字段能自动调用trim()方法。这一功能在处理用户输入时尤其有用,可以确保去除字符串前后的空白字符。

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

代码模板

在使用mybatis时,发现自动生成工具有一个功能:对setter方法中字符串对象,将自动使用trim()方法。这是一个不错的设计,所以我尝试使用最简单的方式实现这个功能,最后使用了idea的模板方法。

#set($paramName = $helper.getParamName($field, $project))
#if($field.modifierStatic)
static ##
#end
void set$StringUtil.capitalizeWithJavaBeanConvention($StringUtil.sanitizeJavaIdentifier($helper.getPropertyName($field, $project)))($field.type $paramName) {
#if ($field.name == $paramName)
    #if (!$field.modifierStatic)
    this.##
    #else
        $classname.##
    #end
#end
$field.name = ##
#if($field.string)
    $paramName == null ? null : $paramName.##
    trim();
#else
    $paramName;
#end
}

将这个代码放到生成setter方法的模板里,在使用时,选择就好,现在使用ubuntu,没法上传图片,就复制结果吧。

public class UserInfo {
    private Long id;
    private String name;
    private String address;
    private String mobile;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name == null ? null : name.trim();
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address == null ? null : address.trim();
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile == null ? null : mobile.trim();
    }
}
package com.teacher.controller; import com.teacher.model.dto.AiRequest; import com.teacher.model.dto.TeachingPlanDto; import com.teacher.service.AiService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/api/ai") public class AiController { private final AiService aiService; @Autowired public AiController(AiService aiService) { this.aiService = aiService; } // 生成课程设计内容 @PostMapping("/course-design") public ResponseEntity<String> generateCourseDesign(@RequestBody TeachingPlanDto planDto) { String designContent = aiService.generateCourseDesign( planDto.getSubject(), planDto.getKnowledgePoints() ); return ResponseEntity.ok(designContent); } // 生成教学计划 @PostMapping("/teaching-plan") public ResponseEntity<TeachingPlanDto> generateTeachingPlan(@RequestBody AiRequest request) { TeachingPlanDto plan = aiService.generateTeachingPlan( request.getSubject(), request.getKeywords() ); return ResponseEntity.ok(plan); } // 分析学生答案 @PostMapping("/analyze-answer") public ResponseEntity<String> analyzeStudentAnswer( @RequestParam String question, @RequestParam String studentAnswer, @RequestParam String correctAnswer) { String analysis = aiService.analyzeAnswer(question, studentAnswer, correctAnswer); return ResponseEntity.ok(analysis); } } 出现了无法解析 'AiService' 中的方法 'generateCourseDesign'、无法解析 'TeachingPlanDto' 中的方法 'getKnowledgePoints'、无法解析 'AiService' 中的方法 'generateTeachingPlan'、无法解析 'AiRequest' 中的方法 'getSubject'、无法解析 'AiRequest' 中的方法 'getKeywords'、无法解析 'AiService' 中的方法 'analyzeAnswer' AiRequest的代码如下package com.teacher.model.dto; import lombok.Getter; import lombok.Setter; @Getter @Setter public class AiRequest { private String prompt; // 用户输入的提示词 private String context; // 上下文信息(可选) private String model; // 使用的模型 private int maxTokens; // 最大生成token数 private double temperature; // 生成温度(0-1) private boolean stream; // 是否流式输出 private String userId; // 用户ID(用于个性化生成) // 添加构造方法简化创建 public AiRequest(String prompt) { this.prompt = prompt; } public AiRequest(String prompt, String context) { this.prompt = prompt; this.context = context; } } TeachingPlanDto的代码如下package com.teacher.model.dto; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class TeachingPlanDto { private String planId; // 计划ID private String teacherId; // 教师ID private String subject; // 学科 private String gradeLevel; // 年级 private String title; // 计划标题 private String description; // 计划描述 private String duration; // 计划时长(如:4周) private List<TeachingUnit> units; // 教学单元列表 @Getter @Setter public static class TeachingUnit { private int sequence; // 单元序号 private String topic; // 主题 private String objectives; // 教学目标 private List<String> knowledgePoints; // 关联的知识点ID列表 private List<String> resources; // 资源列表(课件、习题等) private String assessmentMethod; // 评估方法 } } AiServiceImpl的代码如下package com.teacher.service.Impl; import com.teacher.exception.AIServiceException; import com.teacher.model.dto.AiRequest; import com.teacher.model.dto.AiResponse; import com.teacher.util.QwenClient; import com.google.common.util.concurrent.RateLimiter; import com.teacher.service.AiService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; @Service public class AiServiceImpl implements AiService { private static final double AI_RATE_LIMIT = 5.0; // 5 requests per second private final QwenClient qwenClient; private final RateLimiter rateLimiter = RateLimiter.create(AI_RATE_LIMIT); @Autowired public AiServiceImpl(QwenClient qwenClient) { this.qwenClient = qwenClient; } @Override public AiResponse chatWithAI(AiRequest request) { try { // 限流保护 if (!rateLimiter.tryAcquire(1, TimeUnit.SECONDS)) { throw new AIServiceException("AI服务请求过载,请稍后再试"); } // 调用AI服务 String response = qwenClient.callQwenApi(request.getPrompt()); return new AiResponse(response, System.currentTimeMillis()); } catch (Exception e) { throw new AIServiceException("AI服务调用失败", e); } } @Override public String generateSummary(String content, int maxLength) { String prompt = String.format( "请为以下内容生成一个简洁的摘要,不超过%d个字符:\n\n%s", maxLength, content ); return callQwenApiWithRetry(prompt, 2); } @Override public List<String> extractKnowledgePoints(String content) { String prompt = String.format( "请从以下教学内容中提取关键知识点,每个知识点用短句表示,按重要性排序:\n\n%s", content ); String response = callQwenApiWithRetry(prompt, 2); return parseKnowledgePoints(response); } @Override public String correctText(String text) { String prompt = String.format( "请校对以下文本,修正语法、拼写和标点错误,保持原意不变:\n\n%s", text ); return callQwenApiWithRetry(prompt, 1); } @Override public String generateMultimediaContent(String prompt, String mediaType) { String fullPrompt = String.format( "根据以下描述生成%s内容:\n%s\n\n请使用适合%s的格式输出", mediaType, prompt, mediaType ); return callQwenApiWithRetry(fullPrompt, 2); } private String callQwenApiWithRetry(String prompt, int maxRetries) { int attempt = 0; while (attempt < maxRetries) { try { return qwenClient.callQwenApi(prompt); } catch (Exception e) { attempt++; if (attempt >= maxRetries) { throw new AIServiceException("AI服务调用失败,重试次数已用完", e); } // 指数退避重试 try { Thread.sleep((long) (Math.pow(2, attempt) * 1000)); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } } } return "AI服务暂时不可用"; } private List<String> parseKnowledgePoints(String response) { List<String> points = new ArrayList<>(); String[] lines = response.split("\n"); for (String line : lines) { if (line.matches("^\\d+\\.\\s+.+")) { points.add(line.substring(line.indexOf('.') + 1).trim()); } } return points; } }
最新发布
07-12
在面向对象编程中,getter 和 setter 方法的代码格式化和规范对于保持代码的一致性和可读性至关重要。以下是关于 getter 和 setter 方法的一些常见格式化规范和最佳实践: ### 代码格式化规范 1. **命名规范**: - Getter 方法的命名应遵循 `getPropertyName` 的格式,其中 `PropertyName` 是属性名,首字母大写。 - 对于布尔类型的属性,Getter 方法可以命名为 `isPropertyName`。 - Setter 方法的命名应遵循 `setPropertyName` 的格式。 2. **访问修饰符**: - Getter 和 Setter 方法通常被声明为 `public`,以便外部类可以访问和修改私有属性。 3. **返回类型**: - Getter 方法的返回类型应与属性的类型一致。 - Setter 方法的返回类型通常是 `void`。 4. **参数**: - Setter 方法应该接受一个与属性类型相同的参数。 5. **代码格式**: - 方法体中的代码应简洁明了,直接返回或设置属性值。 6. **空值处理**: - 在返回字符串、列表等可能为 `null` 的属性时,可以考虑返回默认值(如空字符串或空列表)以避免 `NullPointerException`。 7. **验证逻辑**: - 在 Setter 方法中,可以加入额外的验证逻辑来确保数据的有效性。 ### 示例代码 以下是一个符合上述规范的 Java 类示例,展示了如何正确编写 getter 和 setter 方法: ```java public class Order { // 成员变量 private String orderId; private double total; private int count; // 构造方法 public Order() { // 初始化逻辑 } public Order(String orderId, double total, int count) { this.orderId = orderId; this.total = total; this.count = count; } // Getter 和 Setter 方法 public String getOrderId() { return orderId == null ? "" : orderId.trim(); } public void setOrderId(String orderId) { this.orderId = orderId; } public double getTotal() { return total == 0 ? 0 : total; } public void setTotal(double total) { if (total < 0) { throw new IllegalArgumentException("Total cannot be negative"); } this.total = total; } public int getCount() { return count == 0 ? 0 : count; } public void setCount(int count) { if (count < 0) { throw new IllegalArgumentException("Count cannot be negative"); } this.count = count; } } ``` ### 自定义模板 在使用 IDE 如 IntelliJ IDEA 时,可以通过自定义模板自动生成符合特定格式的 getter 和 setter 方法。例如,可以在模板中指定如何处理字符串、数值和列表类型的属性,确保生成的代码符合项目规范 [^3]。 ### 相关问题 1. 如何在 Python 中实现类似 Java 的 getter 和 setter 方法? 2. 如何在 IntelliJ IDEA 中自定义生成 getter 和 setter 方法的模板? 3. 在编写 getter 和 setter 方法时,有哪些常见的错误需要避免? 4. 为什么在 setter 方法中加入验证逻辑是重要的? 5. 如何通过 getter 和 setter 方法提高代码的安全性和可维护性?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值