Java: What scenarios call for the use of reflection?

前端 未结 7 1076
无人共我
无人共我 2020-12-29 10:42

So from reading some of the articles, the message i got out of it was being able to modify fields and set values to classes in real time without recompiling.

so is i

相关标签:
7条回答
  • 2020-12-29 11:01

    Any time you're dealing with a string at runtime and want to treat part of that string as an identifier in the language.

    1. Remote procedure calling -- treat part of a message received over the network as a method name.
    2. Serialization and deserialization -- convert field names to string so you can write the object's fields to a stream and later convert it back into an object.
    3. Object-relational mappings -- maintain a relationship between fields in an object and columns in a database.
    4. Interfaces with dynamically typed scripting languages -- turn a string value produced by a scripting language into a reference to a field or method on an object.

    It can also be used to allow language features to be emulated in the language. Consider the command line java com.example.MyClass which turns a string into a class name. This doesn't require reflection, because the java executable can turn a .class file into code, but without reflection it would not be able to write java com.example.Wrapper com.example.MyClass where Wrapper delegates to its argument as in:

    class Wrapper {
      public static void main(String... argv) throws Exception {
        // Do some initialization or other work.
        Class<?> delegate = Class.forName(argv[0]);
        Method main = delegate.getMethod("main", String[].class);
        main.apply(null, Arrays.asList(argv).subList(1, argv.length).toArray(argv));
      }
    }
    
    0 讨论(0)
  • 2020-12-29 11:05

    I was asked to create a solution for the below statement.

    "1) A diff service that: • can calculate the differences between two objects and return the resulting "diff" • can apply a previously created "diff" against an original object, so that the returned object matches the modified object that was used to calculate the diff. "

    This would have been very difficult without using reflection. Using reflection I could list all the unknown object's Class elements, properties and methods. I could use these to get the values contained in the object. I could compare the original and modified objects values, create "diff" object reflecting changes between the two objects.

    Using Java reflection I could then read the instructions in the "diff" object and apply these to the original object. Java reflection gave me the tools needed to change the values on the unknown properties of the original object. I could invoke setter methods and instantiate types where needed if the original property was null to set the modified value on the original object.

    The "diff" app works on any two objects of the same type, but they could be any type, both objects just have to be of the same type.

    Reflection is very powerful and allow us to create true generic polymorphic methods, functions, libraries and system, where the passed object type does not need to be known at compile time. This applies when using Java Reflection and Generics together, a very powerful combination.

    To end of, I have also used Java Reflection to create a generic sort function, that could sort any list of any Class Type, using any property of the Class as the sort key.As long as the calling method passed the list and the property name to use, the method would return a sorted list.

    0 讨论(0)
  • 2020-12-29 11:11

    Injection frameworks like Guice or Spring use reflection to help you build instances of objects at runtime.

    0 讨论(0)
  • 2020-12-29 11:13

    One other case developing IDEs like eclipse/netbeans etc., to determine which methods in an abstract class need to be implemented by a child class, and automatically write the missing method calls for you (one example).

    0 讨论(0)
  • 2020-12-29 11:16

    Reflection is also useful in cases where configuration is required to string things together. For example, in an application I wrote I have a @Report("debits") annotation that is simply added to methods that generate reports. Then, in the XML configuration a user can simply add:

    <requiredReports="debits,blah,another"/>
    

    This minimizes boiler plate code from mapping the XML code to the actual method, since reflection can discover the report methods and make it available directly.

    0 讨论(0)
  • 2020-12-29 11:17

    Reflection is used when it is needed to get into the other classes in deeper level. So in most of the cases, these implementors have the container-behavior. For instance, dependency injection is mostly done with the use of reflection. If you need a framework as an example for that, Spring does its dependency injection jobs with the help of reflection API.

    You will also find reflections used behind the scenes in a large number of areas. For example, if you used JAXB, then a lot of the marshalling / unmarshalling of the XML will be done using reflections. Using Annotations in your code often results in reflections being used behind the scenes. When performing unit testing, particularly when mocking classes and/or methods, often has lots of reflections code being used.

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