setPropetry练习,使用动作标记,输出学生姓名性别和年龄
时间: 2024-03-19 08:46:24 浏览: 15
好的,以下是一个示例代码:
```java
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
public class Main {
public static void main(String[] args) {
Student student = new Student();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(Student.class);
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
if ("name".equals(propertyDescriptor.getName())) {
propertyDescriptor.getWriteMethod().invoke(student, "张三");
}
if ("sex".equals(propertyDescriptor.getName())) {
propertyDescriptor.getWriteMethod().invoke(student, "男");
}
if ("age".equals(propertyDescriptor.getName())) {
propertyDescriptor.getWriteMethod().invoke(student, 18);
}
}
System.out.println("姓名:" + student.getName() + ",性别:" + student.getSex() + ",年龄:" + student.getAge());
} catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
```
这个示例代码使用了Java的反射机制,通过`Introspector`和`PropertyDescriptor`类获取了`Student`类的属性信息,并使用`getWriteMethod()`方法获取了属性的setter方法,最后通过`invoke()`方法调用setter方法为属性设置值。最终输出了学生的姓名、性别和年龄。