What is reflection and why is it useful?

前端 未结 21 2831
春和景丽
春和景丽 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:47

    Java Reflection is quite powerful and can be very useful. Java Reflection makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.

    A quick Java Reflection example to show you what using reflection looks like:

    Method[] methods = MyObject.class.getMethods();
    
        for(Method method : methods){
            System.out.println("method = " + method.getName());
        }
    

    This example obtains the Class object from the class called MyObject. Using the class object the example gets a list of the methods in that class, iterates the methods and print out their names.

    Exactly how all this works is explained here

    Edit: After almost 1 year I am editing this answer as while reading about reflection I got few more uses of Reflection.

    • Spring uses bean configuration such as:


    
        
    
    

    When the Spring context processes this < bean > element, it will use Class.forName(String) with the argument "com.example.Foo" to instantiate that Class.

    It will then again use reflection to get the appropriate setter for the < property > element and set its value to the specified value.

    • Junit uses Reflection especially for testing Private/Protected methods.

    For Private methods,

    Method method = targetClass.getDeclaredMethod(methodName, argClasses);
    method.setAccessible(true);
    return method.invoke(targetObject, argObjects);
    

    For private fields,

    Field field = targetClass.getDeclaredField(fieldName);
    field.setAccessible(true);
    field.set(object, value);
    

提交回复
热议问题