一个班级类Clazz,里面有两个属性:班级号、班级名称。 一个学生类Student,里面有如下属性:学号、姓名、所在班级、选修课程。 使用setter方法为属性注入值,测试学生类的各个属性注入情况。 使用xml和注解两种方式完成
时间: 2024-10-01 21:08:17 浏览: 42
java实现一个扫描包的工具类实例代码
首先,我们创建一个简单的班级类`Clazz`和学生类`Student`:
```java
// 班级类 (Clazz)
public class Clazz {
private String className;
private int classNumber;
// 构造函数和setter/getter
public Clazz(String className, int classNumber) {
this.className = className;
this.classNumber = classNumber;
}
// Getter and Setter methods
public String getClassName() { return className; }
public void setClassName(String className) { this.className = className; }
public int getClassNumber() { return classNumber; }
public void setClassNumber(int classNumber) { this.classNumber = classNumber; }
}
// 学生类 (Student)
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.List;
@XmlRootElement(name = "student")
public class Student {
private String studentId;
private String name;
private Clazz clazz;
private List<String> selectedCourses; // 假设课程名作为字符串
public Student(String studentId, String name, Clazz clazz) {
this.studentId = studentId;
this.name = name;
this.clazz = clazz;
this.selectedCourses = new ArrayList<>();
}
// Getter and Setter methods
public String getStudentId() { return studentId; }
public void setStudentId(String studentId) { this.studentId = studentId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Clazz getClazz() { return clazz; }
public void setClazz(Clazz clazz) { this.clazz = clazz; }
// 添加选修课程的方法
public void addSelectedCourse(String courseName) {
this.selectedCourses.add(courseName);
}
// ...其他getter和setter省略
}
```
接下来,我们可以分别通过XML注解的方式设置属性值以及使用setter方法来测试:
**XML注解方式测试:**
```java
// XML配置文件 (假设为student.xml)
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.File;
JAXBContext context = JAXBContext.newInstance(Student.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File xmlFile = new File("path_to_your_xml_file.xml");
Student student = (Student) unmarshaller.unmarshal(xmlFile);
System.out.println("Student ID: " + student.getStudentId());
System.out.println("Name: " + student.getName());
System.out.println("Class Number: " + student.getClazz().getClassNumber());
System.out.println("Selected Courses: " + student.getSelectedCourses());
```
**setter方法方式测试:**
```java
// 创建并设置属性值
Clazz myClazz = new Clazz("高一", 101);
Student myStudent = new Student("123456", "张三", myClazz);
myStudent.setStudentId("123456789");
myStudent.setName("李四");
myStudent.addSelectedCourse("数学");
System.out.println("Student ID: " + myStudent.getStudentId());
System.out.println("Name: " + myStudent.getName());
System.out.println("Class Number: " + myStudent.getClazz().getClassNumber());
System.out.println("Selected Course: " + myStudent.getSelectedCourses().get(0));
```
阅读全文