按照如下要求,编写程序: 1、创建Student类,其中包含3个属性name、age、hometown。 2、创建3个自定义属性注解类@StudentName、@StudentAge、@Hometown,运行周期设置为运行时。 3、将2、中定义的3个注解对Student类的3个属性进行注解,并进行赋值。 4、创建测试类,对Student类进行反射操作,解析定义的注解并将注解中定义的值输出。
时间: 2024-02-10 14:15:44 浏览: 32
好的,我已经了解您的要求了。下面是相应的Java代码实现:
Student类:
```java
public class Student {
@StudentName(name = "张三")
private String name;
@StudentAge(age = 18)
private int age;
@Hometown(hometown = "北京")
private String hometown;
// 省略getter和setter方法
}
```
自定义注解类:
```java
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentName {
String name() default "";
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface StudentAge {
int age() default 0;
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Hometown {
String hometown() default "";
}
```
测试类:
```java
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) {
Student student = new Student();
// 获取Student类中所有的属性
Field[] fields = student.getClass().getDeclaredFields();
for (Field field : fields) {
// 判断属性上是否有@StudentName注解
if (field.isAnnotationPresent(StudentName.class)) {
// 获取@StudentName注解中定义的name值
StudentName studentName = field.getAnnotation(StudentName.class);
System.out.println("姓名:" + studentName.name());
}
// 判断属性上是否有@StudentAge注解
if (field.isAnnotationPresent(StudentAge.class)) {
// 获取@StudentAge注解中定义的age值
StudentAge studentAge = field.getAnnotation(StudentAge.class);
System.out.println("年龄:" + studentAge.age());
}
// 判断属性上是否有@Hometown注解
if (field.isAnnotationPresent(Hometown.class)) {
// 获取@Hometown注解中定义的hometown值
Hometown hometown = field.getAnnotation(Hometown.class);
System.out.println("家乡:" + hometown.hometown());
}
}
}
}
```
输出结果:
```
姓名:张三
年龄:18
家乡:北京
```
希望能够帮助到您!