About avoiding the effect of reflection on logic

problem

Today I asked: We know that Java reflection can get the objects in the system, and then call the methods of these objects, or even modify the attribute values ​​of the objects, then today ’s question is: how do we write when we write classes Code that is less affected by reflection. To put it simply, when it is called by reflection, there are fewer flashbacks, confusion and other situations. Furthermore, what does this have to do with our daily coding?

answer

First, let's see what reflection can do:

  1. Freely call the constructor to create objects;
  2. Freely call the method of the object;
  3. Freely modify various properties of objects.

For the first point, our enlightenment is that after writing the constructor of the class, we need to understand which attributes may be empty; thus, in each method, there may be corresponding treatment for the case of possible empty;

For the second point, our code is best not to anticipate that some methods will be executed in order, because we may be able to guarantee this when we first write, but in the process of iterative modification of the code, this point may not be guaranteed, and There are some unexpected bugs;

For the third point, it is best not to judge some familiar values ​​through the logic of the code, because maybe when we originally wrote, the attribute must have a value. Similarly, when iterating, the attribute value may be null. .

It is best to share a common processing method of Java source code:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
  ...
}

This is a little sketch of the HashMap source code. You can see that he uses a tab variable to save the table. The advantage of this is that after the subsequent table refers to other objects, the execution of this method will not be affected. Prevent unknown errors caused by multi-thread concurrency.

Published 19 original articles · praised 8 · visits 4040

Guess you like

Origin blog.csdn.net/u014068277/article/details/103951227