What is reflection and why is it useful?

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

    Reflection allows instantiation of new objects, invocation of methods, and get/set operations on class variables dynamically at run time without having prior knowledge of its implementation.

    Class myObjectClass = MyObject.class;
    Method[] method = myObjectClass.getMethods();
    
    //Here the method takes a string parameter if there is no param, put null.
    Method method = aClass.getMethod("method_name", String.class); 
    
    Object returnValue = method.invoke(null, "parameter-value1");
    

    In above example the null parameter is the object you want to invoke the method on. If the method is static you supply null. If the method is not static, then while invoking you need to supply a valid MyObject instance instead of null.

    Reflection also allows you to access private member/methods of a class:

    public class A{
    
      private String str= null;
    
      public A(String str) {
      this.str= str;
      }
    }
    

    .

    A obj= new A("Some value");
    
    Field privateStringField = A.class.getDeclaredField("privateString");
    
    //Turn off access check for this field
    privateStringField.setAccessible(true);
    
    String fieldValue = (String) privateStringField.get(obj);
    System.out.println("fieldValue = " + fieldValue);
    
    • For inspection of classes (also know as introspection) you don't need to import the reflection package (java.lang.reflect). Class metadata can be accessed through java.lang.Class.

    Reflection is a very powerful API but it may slow down the application if used in excess, as it resolves all the types at runtime.

提交回复
热议问题