Accessing non-visible classes with reflection

前端 未结 5 711
[愿得一人]
[愿得一人] 2020-12-04 17:23

I am trying to get an instance of a non-visible class, AKA package private class, using reflection. I was wondering if there was a way to switch the modifiers to make it pu

5条回答
  •  星月不相逢
    2020-12-04 17:55

    I had requirement to copy the value of field from older version of object if the value is null in latest version. We had these 2 options.

    Core Java :

    for (Field f : object.getClass().getSuperclass().getDeclaredFields()) {
        f.setAccessible(true);
      System.out.println(f.getName());
      if (f.get(object) == null){
        f.set(object, f.get(oldObject));
      }
    }
    

    Using Spring [org.springframework.beans.BeanWrapper] :

    BeanWrapper bw = new BeanWrapperImpl(object);
    PropertyDescriptor[] data = bw.getPropertyDescriptors();
    for (PropertyDescriptor propertyDescriptor : data) {
      System.out.println(propertyDescriptor.getName());
      Object propertyValue = bw.getPropertyValue(propertyDescriptor.getName());
      if(propertyValue == null )
        bw.setPropertyValue( new PropertyValue(propertyDescriptor.getName(),"newValue"));
    }
    

提交回复
热议问题