在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方法在各種場景下都有廣泛的應用,它們用于獲取類的屬性值,以便在其他類中使用這些屬性。