在Java实际项目中,get方法通常用于获取类的属性值。以下是一些常见的应用案例:
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class Person implements Serializable {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
public class EmployeeDTO {
private String employeeId;
private String employeeName;
public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
public class UserService {
public String getUserName(User user) {
return user.getName();
}
public int getUserAge(User user) {
return user.getAge();
}
}
@RestController
public class UserController {
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") int id) {
// 根据id查询用户信息
User user = userService.getUserById(id);
return user;
}
}
总之,在实际项目中,get方法在各种场景下都有广泛的应用,它们用于获取类的属性值,以便在其他类中使用这些属性。