Java反射:如何获得Java类的所有getter方法并调用它们



我写了一个java类,它有很多getter ..现在我想得到所有的getter方法,并调用他们的时候..我知道有方法,如getMethods()或getMethod(字符串名称,类…parameterTypes),但我只是想得到getter确实…,使用正则表达式?有人能告诉我吗?谢谢!

不要用正则表达式,用Introspector:

for(PropertyDescriptor propertyDescriptor : 
    Introspector.getBeanInfo(yourClass).getPropertyDescriptors()){
    // propertyEditor.getReadMethod() exposes the getter
    // btw, this may be null if you have a write-only property
    System.out.println(propertyDescriptor.getReadMethod());
}

通常你不需要Object.class的属性,所以你会使用带有两个参数的方法:

Introspector.getBeanInfo(yourClass, stopClass)
// usually with Object.class as 2nd param
// the first class is inclusive, the second exclusive

顺便说一句:有框架可以为你做这些,并为你提供一个高级视图。如。Commons/beanutils有

方法
Map<String, String> properties = BeanUtils.describe(yourObject);

(这里的docs),它的作用是:查找并执行所有getter,并将结果存储在map中。不幸的是,BeanUtils.describe()在返回之前将所有属性值转换为string。WTF。由于@danw


更新:

这是一个基于对象bean属性返回Map<String, Object>的Java 8方法。

public static Map<String, Object> beanProperties(Object bean) {
  try {
    return Arrays.asList(
         Introspector.getBeanInfo(bean.getClass(), Object.class)
                     .getPropertyDescriptors()
      )
      .stream()
      // filter out properties with setters only
      .filter(pd -> Objects.nonNull(pd.getReadMethod()))
      .collect(Collectors.toMap(
        // bean property name
        PropertyDescriptor::getName,
        pd -> { // invoke method to get value
            try { 
                return pd.getReadMethod().invoke(bean);
            } catch (Exception e) {
                // replace this with better error handling
               return null;
            }
        }));
  } catch (IntrospectionException e) {
    // and this, too
    return Collections.emptyMap();
  }
}
但是,您可能希望使错误处理更健壮。对于样板文件,很抱歉,检查异常阻止我们在这里完全发挥功能。

原来collections . tomap()讨厌空值。下面是上面代码的一个更命令式的版本:

public static Map<String, Object> beanProperties(Object bean) {
    try {
        Map<String, Object> map = new HashMap<>();
        Arrays.asList(Introspector.getBeanInfo(bean.getClass(), Object.class)
                                  .getPropertyDescriptors())
              .stream()
              // filter out properties with setters only
              .filter(pd -> Objects.nonNull(pd.getReadMethod()))
              .forEach(pd -> { // invoke method to get value
                  try {
                      Object value = pd.getReadMethod().invoke(bean);
                      if (value != null) {
                          map.put(pd.getName(), value);
                      }
                  } catch (Exception e) {
                      // add proper error handling here
                  }
              });
        return map;
    } catch (IntrospectionException e) {
        // and here, too
        return Collections.emptyMap();
    }
}

下面以更简洁的方式使用JavaSlang:

实现相同的功能
public static Map<String, Object> javaSlangBeanProperties(Object bean) {
    try {
        return Stream.of(Introspector.getBeanInfo(bean.getClass(), Object.class)
                                     .getPropertyDescriptors())
                     .filter(pd -> pd.getReadMethod() != null)
                     .toJavaMap(pd -> {
                         try {
                             return new Tuple2<>(
                                     pd.getName(),
                                     pd.getReadMethod().invoke(bean));
                         } catch (Exception e) {
                             throw new IllegalStateException();
                         }
                     });
    } catch (IntrospectionException e) {
        throw new IllegalStateException();
    }
}

这是番石榴的版本:

public static Map<String, Object> guavaBeanProperties(Object bean) {
    Object NULL = new Object();
    try {
        return Maps.transformValues(
                Arrays.stream(
                        Introspector.getBeanInfo(bean.getClass(), Object.class)
                                    .getPropertyDescriptors())
                      .filter(pd -> Objects.nonNull(pd.getReadMethod()))
                      .collect(ImmutableMap::<String, Object>builder,
                               (builder, pd) -> {
                                   try {
                                       Object result = pd.getReadMethod()
                                                         .invoke(bean);
                                       builder.put(pd.getName(),
                                                   firstNonNull(result, NULL));
                                   } catch (Exception e) {
                                       throw propagate(e);
                                   }
                               },
                               (left, right) -> left.putAll(right.build()))
                      .build(), v -> v == NULL ? null : v);
    } catch (IntrospectionException e) {
        throw propagate(e);
    }
}

您可以使用Reflections框架来实现

import org.reflections.ReflectionUtils.*;
Set<Method> getters = ReflectionUtils.getAllMethods(someClass,
      ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withPrefix("get"));

Spring为Bean内省提供了一个简单的BeanUtil方法:

PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(clazz, property);
Method getter = pd.getReadMethod();
 // Get the Class object associated with this class.
    MyClass myClass= new MyClass ();
    Class objClass= myClass.getClass();
    // Get the public methods associated with this class.
    Method[] methods = objClass.getMethods();
    for (Method method:methods)
    {
        System.out.println("Public method found: " +  method.toString());
    }

为什么不使用简单的Java呢?…

public static Map<String, Object> beanProperties(final Object bean) {
    final Map<String, Object> result = new HashMap<String, Object>();
    try {
        final PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass(), Object.class).getPropertyDescriptors();
        for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
            final Method readMethod = propertyDescriptor.getReadMethod();
            if (readMethod != null) {
                result.put(propertyDescriptor.getName(), readMethod.invoke(bean, (Object[]) null));
            }
        }
    } catch (Exception ex) {
        // ignore
    }
    return result;
}

代码测试正常

private void callAllGetterMethodsInTestModel(TestModel testModelObject) {
        try {
            Class testModelClass = Class.forName("com.example.testreflectionapi.TestModel");
            Method[] methods = testModelClass.getDeclaredMethods();
            ArrayList<String> getterResults = new ArrayList<>();
            for (Method method :
                    methods) {
                if (method.getName().startsWith("get")){
                    getterResults.add((String) method.invoke(testModelObject));
                }
            }
            Log.d("sayanReflextion", "==>: "+getterResults.toString());
        } catch (ClassNotFoundException | IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }
public static void retrieveAndExecuteBeanGetterMethods(Object bean) throws IntrospectionException {
    List<PropertyDescriptor> beanGettersList = Arrays.asList(
            Introspector.getBeanInfo(bean.getClass(), Object.class)
                    .getPropertyDescriptors());
    beanGettersList.stream()
            .filter(pd -> Objects.nonNull(pd.getReadMethod()))
            .collect(Collectors.toMap(PropertyDescriptor::getName,
                    pd -> {
                        try {
                            return pd.getReadMethod().invoke(bean);
                        } catch (Exception e) {
                            return null;
                        }
                    }));
}

相关内容

  • 没有找到相关文章

最新更新