What is reflection and why is it useful?

前端 未结 21 2874
春和景丽
春和景丽 2020-11-21 04:36

What is reflection, and why is it useful?

I\'m particularly interested in Java, but I assume the principles are the same in any language.

相关标签:
21条回答
  • 2020-11-21 04:41

    One of my favorite uses of reflection is the below Java dump method. It takes any object as a parameter and uses the Java reflection API to print out every field name and value.

    import java.lang.reflect.Array;
    import java.lang.reflect.Field;
    
    public static String dump(Object o, int callCount) {
        callCount++;
        StringBuffer tabs = new StringBuffer();
        for (int k = 0; k < callCount; k++) {
            tabs.append("\t");
        }
        StringBuffer buffer = new StringBuffer();
        Class oClass = o.getClass();
        if (oClass.isArray()) {
            buffer.append("\n");
            buffer.append(tabs.toString());
            buffer.append("[");
            for (int i = 0; i < Array.getLength(o); i++) {
                if (i < 0)
                    buffer.append(",");
                Object value = Array.get(o, i);
                if (value.getClass().isPrimitive() ||
                        value.getClass() == java.lang.Long.class ||
                        value.getClass() == java.lang.String.class ||
                        value.getClass() == java.lang.Integer.class ||
                        value.getClass() == java.lang.Boolean.class
                        ) {
                    buffer.append(value);
                } else {
                    buffer.append(dump(value, callCount));
                }
            }
            buffer.append(tabs.toString());
            buffer.append("]\n");
        } else {
            buffer.append("\n");
            buffer.append(tabs.toString());
            buffer.append("{\n");
            while (oClass != null) {
                Field[] fields = oClass.getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    buffer.append(tabs.toString());
                    fields[i].setAccessible(true);
                    buffer.append(fields[i].getName());
                    buffer.append("=");
                    try {
                        Object value = fields[i].get(o);
                        if (value != null) {
                            if (value.getClass().isPrimitive() ||
                                    value.getClass() == java.lang.Long.class ||
                                    value.getClass() == java.lang.String.class ||
                                    value.getClass() == java.lang.Integer.class ||
                                    value.getClass() == java.lang.Boolean.class
                                    ) {
                                buffer.append(value);
                            } else {
                                buffer.append(dump(value, callCount));
                            }
                        }
                    } catch (IllegalAccessException e) {
                        buffer.append(e.getMessage());
                    }
                    buffer.append("\n");
                }
                oClass = oClass.getSuperclass();
            }
            buffer.append(tabs.toString());
            buffer.append("}\n");
        }
        return buffer.toString();
    }
    
    0 讨论(0)
  • 2020-11-21 04:42

    Reflection is a language's ability to inspect and dynamically call classes, methods, attributes, etc. at runtime.

    For example, all objects in Java have the method getClass(), which lets you determine the object's class even if you don't know it at compile time (e.g. if you declared it as an Object) - this might seem trivial, but such reflection is not possible in less dynamic languages such as C++. More advanced uses lets you list and call methods, constructors, etc.

    Reflection is important since it lets you write programs that do not have to "know" everything at compile time, making them more dynamic, since they can be tied together at runtime. The code can be written against known interfaces, but the actual classes to be used can be instantiated using reflection from configuration files.

    Lots of modern frameworks use reflection extensively for this very reason. Most other modern languages use reflection as well, and in scripting languages (such as Python) they are even more tightly integrated, since it feels more natural within the general programming model of those languages.

    0 讨论(0)
  • 2020-11-21 04:45

    I just want to add some point to all that was listed.

    With Reflection API you can write universal toString() method for any object.

    It is useful at debugging.

    Here is some example:

    class ObjectAnalyzer {
    
       private ArrayList<Object> visited = new ArrayList<Object>();
    
       /**
        * Converts an object to a string representation that lists all fields.
        * @param obj an object
        * @return a string with the object's class name and all field names and
        * values
        */
       public String toString(Object obj) {
          if (obj == null) return "null";
          if (visited.contains(obj)) return "...";
          visited.add(obj);
          Class cl = obj.getClass();
          if (cl == String.class) return (String) obj;
          if (cl.isArray()) {
             String r = cl.getComponentType() + "[]{";
             for (int i = 0; i < Array.getLength(obj); i++) {
                if (i > 0) r += ",";
                Object val = Array.get(obj, i);
                if (cl.getComponentType().isPrimitive()) r += val;
                else r += toString(val);
             }
             return r + "}";
          }
    
          String r = cl.getName();
          // inspect the fields of this class and all superclasses
          do {
             r += "[";
             Field[] fields = cl.getDeclaredFields();
             AccessibleObject.setAccessible(fields, true);
             // get the names and values of all fields
             for (Field f : fields) {
                if (!Modifier.isStatic(f.getModifiers())) {
                   if (!r.endsWith("[")) r += ",";
                   r += f.getName() + "=";
                   try {
                      Class t = f.getType();
                      Object val = f.get(obj);
                      if (t.isPrimitive()) r += val;
                      else r += toString(val);
                   } catch (Exception e) {
                      e.printStackTrace();
                   }
                }
             }
             r += "]";
             cl = cl.getSuperclass();
          } while (cl != null);
    
          return r;
       }    
    }
    
    0 讨论(0)
  • 2020-11-21 04:45

    Reflection gives you the ability to write more generic code. It allows you to create an object at runtime and call its method at runtime. Hence the program can be made highly parameterized. It also allows introspecting the object and class to detect its variables and method exposed to the outer world.

    0 讨论(0)
  • 2020-11-21 04:46

    As per my understanding:

    Reflection allows programmer to access entities in program dynamically. i.e. while coding an application if programmer is unaware about a class or its methods, he can make use of such class dynamically (at run time) by using reflection.

    It is frequently used in scenarios where a class name changes frequently. If such a situation arises, then it is complicated for the programmer to rewrite the application and change the name of the class again and again.

    Instead, by using reflection, there is need to worry about a possibly changing class name.

    0 讨论(0)
  • 2020-11-21 04:47

    Uses of Reflection

    Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

    Extensibility Features

    An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to ensure a high level of code coverage in a test suite.

    Drawbacks of Reflection

    Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

    • Performance Overhead

    Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications.

    • Security Restrictions

    Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

    • Exposure of Internals

    Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

    source: The Reflection API

    0 讨论(0)
提交回复
热议问题