Java: What scenarios call for the use of reflection?

前端 未结 7 1121
无人共我
无人共我 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));
      }
    }
    

提交回复
热议问题