Life on reflection, Java generics by

Yesterday, a colleague asked UserService, XxxService calls the Dao of insert, update ... ..., these duplicate code, there is no way to become flexible in?

 

Coincidence, and we share the theme coincided, secrecy, leave alone the solutions, it is when nothing had happened, reintroduced today's topic (Wuzui laughs).

 

I want transformation of R & D personnel, occasionally taste of Java source code; workplace well-yard farming, from time to time will also look to build infrastructure projects. In fact, whether you started going ape door, or hardcore God of War, today's share more or less you have heard, concerned about, too confused and even used.

 

Okay, ready small bench, let us talk together, you look at the source code, the process can take architecture to avoid Java is not open those E, T ,? And other letters are What do you mean?

 

First knowledge about science, what is generic? What chat concept, directly on the code, go straight, starting with JDK 1.8 out picking point source, with a face to face generic, mixed a Lian Shu.

 

1. 

What is E?

 

E JDK source code can be said everywhere, it will be chatting about the source ArrayList.

public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
    
    /**
     * Appends the specified element to the end of this list.
     *
     * @param e element to be appended to this list
     * @return <tt>true</tt> (as specified by {@link Collection#add})
     */
    public boolean add(E e) {
        ensureCapacityInternal(size + 1);  // Increments modCount!!
        elementData[size++] = e;
        return true;
    }
    // ... more code ...
}

  

这个 E 在此处用来创建与初始 ArrayList 的类型,其实我们可以把它换成实际的类型,举个栗子:

 

640?wx_fmt=png

 

E found compiler will be replaced by a real type, in fact, that is, when we create ArrayList <String>, then the corresponding add () will turn add (String e); when we create ArrayList <Dog>, then corresponding add () becomes add (Dog e).

 

But often you would be so inattentive to write, so in fact you do not want to write, program ape bitter heart, in fact, that had a clue (Wuzui laughs).

 

640?wx_fmt=png

 

This explains why write code, the compiler does not always often in the past, there are always warnings, Who we defined type String, but we have to go and set it into a dog.

 

Torture from the soul: only use "E" to represent it? ( Close colleagues really asked me this question, I answer this once again seriously )

 

In fact, we can use any legal Java identifier string, but everyone is represented by a single letter, has become a habit, and E also represents the meaning of Element elements in the collection so often used to represent E, but large source probability will encounter the letter T.

 

2. 

What is T?

public static <T extends Comparable<? super T>> void sort(List<T> list) {
    list.sort(null);
}

  

The above excerpt from JDK 1.8 Collections source, we find the "T", but also "?" Question mark we put aside for the time being, focusing chat "T".

 

See two parts, wherein the first portion <T extends Comparable> means that T must implement Comparable ( which is the focus, which is the focus, which is the focus ); a second part of the method into the reference sort (List <T> list ), it refers only pass parameterized type of inherited Comparable list.

 

In fact, it is difficult to understand, might as well pick a chestnut with understanding.

 

640?wx_fmt=png

 

Pick from a source in JDK 1.8 String source, the String substituted into the Collections the Sort method, replaced by T Wu try it and see if ok? ! Variable substitution mathematics we have learned, will not go up.

 

640?wx_fmt=png

 

But the actual development you have not encountered the situation on the map, during the dog sort the list, it is given life and death! Error! ! The reason is because you want to sort of dog, we must implement Comparable, it can only be sorted.

 

Well, T will not talk to you, and we still talk about this question mark now.

 

3.

"? " Question mark is what?

 

Question mark, see this estimate will be forced to look ignorant, in fact, unknown, on behalf of ten thousand kinds of possibilities in Java is the wildcard characters.

 

640?wx_fmt=png

 

Then we look at the above excerpt from JDK 1.8 Collections source, so Comparable <? Super T> Comparable represents the type parameter must be the parent of T or T-type, you may have confused, and then throw or point bar code.

 

640?wx_fmt=png

 

See the results did not, because the dog for sorting, sort of type Dog or Dog must be the parent type, we passed a String, of course, is not compiled by you, or wish to change Dog Object myself to try and see see the effect, which is not demonstration. But the conclusion is to say about: Comparable Comparable represents the type parameter must be a parent of type T or T <super T?>.

 

Mentioned <? Super T>, that have to mention mentioning <? Extends T>, in fact, as long as the above figured it out, this also is very clear, the question marks represent inheritance and implement T , not chestnuts thrown in Source framework encountered know what do you mean on the line.

 

4.

Wayward summary.

 

In fact, a generic inspection compile, it is possible to effectively prevent a dog into a sea, which is divided into classes using the generic method and generic use; wherein E is mainly used for a collection of elements, in addition to the vast E part is T, then Java has introduced a wildcard character is a question mark, but you can use any valid Java identifiers represent, do not tangle, do not tangle, not to tangle.

 

Having said that, we have not yet solved the opening problems ah? Man of few words said, directly throw the code, do not understand it does not matter, pay attention to understand the above letters on the line, the following code share with a friend in need (Whoops I went, and came out letters D).

@Transactional(readOnly = true)
public abstract class CrudService<D extends CrudDao<T>, T extends DataEntity<T>> extends BaseService {
   
   /**
    * Object persistence layer
    */
   @Autowired
   protected D dao;
   
   /**
    * Get a single data
    * @param entity
    * @return
    */
   public T get(T entity) {
      return dao.get(entity);
   }
   
   /**
    * Query list data
    * @param entity
    * @return
    */
   public List<T> findList(T entity) {
      return dao.findList(entity);
   }
   
   /**
    * Query paged data
    * @Param page page objects
    * @param entity
    * @return
    */
   public Page<T> findPage(Page<T> page, T entity) {
      entity.setPage(page);
      page.setList(dao.findList(entity));
      return page;
   }

   /**
    * Save data (insert or update)
    * @param entity
    */
   @Transactional(readOnly = false)
   public int save(T entity) {
      if (entity.getIsNewRecord()){
         entity.preInsert();
         return dao.insert(entity);
      }else{
         entity.preUpdate();
         return dao.update(entity);
      }
   }
   
   /**
    * delete data
    * @param entity
    */
   @Transactional(readOnly = false)
   public int delete(T entity) {
      return dao.delete(entity);
   }
}

 

5.

Well, share it here today, hoping to understand your confused; hope on you along the way to help you through the clutter. If you feel a little assistance, please look in seconds like crazy to share forward, because every time you share, I seriously as the encouragement and love.

 

 

Guess you like

Origin www.cnblogs.com/socoool/p/12629774.html