Java创建学生对象,包括姓名、年龄、住址、出生年月等属性;模拟生成学生集合,基于字段注解、打印输出该集合
时间: 2023-06-07 21:07:58 浏览: 45
没有问题,这是一个关于Java编程方面的问题。以下是示例代码:
```
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface StudentInfo {
String name();
}
class Student {
@StudentInfo(name = "张三")
String name;
int age;
String address;
String birthMonth;
public Student(String name, int age, String address, String birthMonth) {
this.name = name;
this.age = age;
this.address = address;
this.birthMonth = birthMonth;
}
}
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("张三", 20, "北京市昌平区", "1月"));
students.add(new Student("李四", 22, "北京市海淀区", "6月"));
students.add(new Student("王五", 23, "北京市朝阳区", "9月"));
for (Student student : students) {
Class<?> cls = student.getClass();
Field[] fields = cls.getDeclaredFields();
System.out.println("学生信息:");
for (Field field : fields) {
if (field.isAnnotationPresent(StudentInfo.class)) {
StudentInfo annotation = field.getAnnotation(StudentInfo.class);
System.out.println(annotation.name() + ":" + getField(field, student));
}
}
System.out.println();
}
}
private static String getField(Field field, Object object) {
try {
field.setAccessible(true);
Object value = field.get(object);
return value.toString();
} catch (IllegalAccessException e) {
return "unknown";
}
}
}
```
这段代码创建了一个`Student`类,其中包括姓名、年龄、住址、出生年月等属性。使用注解`@StudentInfo`标记了姓名字段。使用反射打印输出学生集合,并基于字段注解打印出学生的姓名信息。
如果您有任何其他问题,可以继续问我。