Dosen't Reflection API break the very purpose of Data encapsulation?

前端 未结 4 467
无人共我
无人共我 2021-01-05 01:31

Very recently I came across the Reflection API and to my surprise we can access and even alter the private variables.I tried the following code

import java.l         


        
4条回答
  •  北荒
    北荒 (楼主)
    2021-01-05 02:04

    Isn't the reflection API changing the very purpose of Data Encapsulation?

    Don't get too hung up on the rules. There are times when it's useful to break them.

    Reflextion is very useful. Take for example my code for logging finding changes so that I can log them to a database:

    public static void log(String userID, Object bOld, Object bNew)
              throws IntrospectionException, IllegalAccessException, InvocationTargetException {
          String res = "";//String to hold the change record
          boolean changed = false;
          try {
            if(bOld != null){ //if this is an update
                BeanInfo beanInfo = Introspector.getBeanInfo(bOld.getClass());
                res = bOld.getClass().getSimpleName() + " - ";
                //loop and compare old values with new values and add them to our string if they are changed
                for (PropertyDescriptor prop : beanInfo.getPropertyDescriptors()) {
                    Method getter = prop.getReadMethod();
                    Object vOld = getter.invoke(bOld); //old value
                    Object vNew = getter.invoke(bNew); //new value
                    if (vOld == vNew || (vOld != null && vOld.equals(vNew))) {
                      continue;
                    }
                    changed = true;
                    res = res + "(" + prop.getName()  + ", " +  vOld  + ", " + vNew + ")";
                }
              }
    

    It's a lot easier to do it this way. If I was using getters I would have to write a seperate method for each class and modify every time a new field was added. With reflection I can just write one method to handle all of my classes. I write about my method for logging changes here

提交回复
热议问题