[java] view plaincopy
- package org.example.reflection;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- /**
- *
- *
- * DOC 使用反射,类似javaBean的操作<br/>
- * 首先获取set方法,然后调用set方法;然后获取get方法,再调用get方法<br/>
- * 在整个过程中,我们都没有显示的使用Person类的某个具体实例
- *
- */
- public class UseReflection {
- public static void main(String[] args) throws Exception {
- Class clazz = new Person().getClass();
- Field[] fields = clazz.getDeclaredFields();
- // 先获取每一个属性,然后调用set和get方法
- Object person = clazz.newInstance();
- for (int i = 0; i < fields.length; i++) {
- Field field = fields[i];
- // 将字段名称的首字母改为大写,这符合javaBean的方法名称拼写标准
- String fieldName = field.getName().substring(0, 1).toUpperCase()
- + field.getName().substring(1, field.getName().length());
- // 获取set方法
- Method setMethod = clazz.getDeclaredMethod("set" + fieldName, field.getType());
- // 调用set方法
- if (fieldName.equals("Name")) {
- setMethod.invoke(person, "张三");
- } else if (fieldName.equals("Sex")) {
- setMethod.invoke(person, "男");
- } else {
- setMethod.invoke(person, 20);
- }
- // 获取get方法
- Method getMethod = clazz.getDeclaredMethod("get" + fieldName, null);
- // 调用get方法
- System.out.println(getMethod.invoke(person, null));
- // test results:
- /**
- * 张三<br/>
- * 男<br/>
- * 20
- */
- }
- }
- }
转载于:https://blog.51cto.com/mrwlh/1093556