When does java-13.7 use generics?
In this section, we will discuss when to use generics?
Answer: When you want code to work across multiple types (different types do not include inheritance relationships.
1. When there is no exact type
The following is the error code:
package com.ray.ch13;public class Test
{private T obj;public Test(T t) {obj = t;}public void test() {// obj.f();//error}}
From the code above, we can see that when there is no exact type, obj cannot call any method.
Correct code:
package com.ray.ch13;public class Test
{private T obj;public Test(T t) {obj = t;}public void test() {obj.say();}}class Person {public void say() {}}
Obj can call related methods only when the boundary of generics is defined.
The reason for the above is that during compilation, the compiler does not know where the specific boundary of T is. Therefore, it is necessary to define the boundary to find the corresponding class and check whether the corresponding method is included, because java contains a pseudo-generic type, the parameter type cannot be seen at the jvm level, so type security must be checked during compilation.
2. When we are of the same type or have an inherited link type
Reference the above Code:
package com.ray.ch13;public class Test
{private T obj;public Test(T t) {obj = t;}public void test() {obj.say();}}class Person {public void say() {}}
The generics in the above Code do not work very effectively, and it increases the difficulty of reading the Code. In fact, we can modify them into the following code with the same functions:
package com.ray.ch13;public class Test {private Person person;public Test(Person person) {this.person = person;}public void test() {person.say();}}class Person {public void say() {}}
The modified code is simpler and clearer. At this time, someone will say that the above Code is extend. You don't have it here, but let's add something to look at it:
package com.ray.ch13;public class Test {private Person person;public Test(Person person) {this.person = person;}public void test() {person.say();}public static void main(String[] args) {new Test(new Man()).test();}}class Person {public void say() {System.out.println("i am a person");}}class Man extends Person {@Overridepublic void say() {System.out.println("i am a man");}}
We create a class that inherits the Person, and then put it in it for method calling.
3. The typical generic example I encountered is the use of generic dao.
The following is a reference to others' dao designs,
Address: http://blog.csdn.net/lazy_p/article/details/5599650
// Universal DAO interface: package com. interval yyy. util. dao; import java. io. serializable; import java. util. collection; import java. util. iterator; import java. util. list; import org. hibernate. criteria; import org. hibernate. lockMode; import org. hibernate. criterion. criterion; import org. hibernate. criterion. detachedCriteria;/*** basic access interface with business data *
* CRUD (create, read, modify, and delete objects) operations on basic data in this interface are independent _ and the resulting DAO can all use these basic instances ** @ author yongtree ** @ date: 2008-03-04 */public interface IBaseDAO {/************************************** * ************************************ --------------- Basic why? Increase? Modify? Delete operation example ----------------------------************************************ ***************************************/ // -------- findById () method? Get (ID id) obtain the entity object ---------------------/*** using ID to obtain the lock mode used by the entity to pair ** @ param id * object identifier * @ param lock * @ return this primary key pair corresponding object */public T findById (ID id, lockMode lock);/*** obtain the object pair through ID ** @ param id * @ return T */public T findById (ID id ); /*** use ID to obtain the entity pair (for the original program compatible with other development members, keep the pair) ** @ param c * @ param id * @ return T */public T findById (Class c, ID id); // ------------- loadById () is to call the load method of hibernate ------------ public T loadById (ID id ); /*** use the id load object ** @ param id * @ param lock * @ return */public T loadById (ID id, LockMode lock ); /*** get all instances ** @ return */public List LoadAll ();/*** Save the entity token ** @ param entity */public T saveEntity (T entity ); /*** update the entity pair *** @ param entity */public void updateEntity (T entity); public void updateEntity (T entity, LockMode lock ); /*** add or update all instances in the Set ** @ param entities */public void saveOrUpdateAll (Collection Entities);/*** Delete multiple instances ** @ param entity * @ throws Exception */public void deleteEntity (T entity); public void deleteEntity (T entity, lockMode lock);/*** Delete the specified object based on the primary key ** @ param id */public void deleteEntityById (ID id); public void deleteEntityById (ID id, LockMode lock ); /*** batch Delete ** @ param entities */public void deleteAll (Collection Entities);/*** update the parameter by merging ** @ param entity * void */public void merge (T entity ); /*************************************** * ********************************** ---------------------- use HQL statement --------------------------------************************************** *************************************//* ** use the HQL statement to check objects ** @ param hsql * query statement * @ return: matching the condition */public T getEntity (String hsql ); /*** use the HQL statement to query ** @ param hsql * query statement * @ return the object set that meets the conditions */public List GetEntities (String hsql);/*** use the HQL statement with parameters to query ** @ param hsql * @ param obj * @ return */public List GetEntities (String hsql, Object [] values); public List GetEntities (String hql, int start, int number); public List GetEntities (String hql, int start, int number, Object [] values ); /*** use the named HQL statement 'batch sorted' ** @ param queryName * @ return */public List FindByNamedQuery (String queryName);/*** use a parameter-based HSQL statement to query the number of records ** @ param queryName * @ param values * @ return */public List FindByNamedQuery (String queryName, Object [] values ); /*** use the HSQL statement named with naming parameters to retrieve the number of records ** @ param queryName * @ param paramNames * @ param values * @ return */public List FindByNamedQuery (String queryName, String [] paramNames, Object [] values);/*** use the HQL statement to query data, return Iterator ** @ param queryString * @ return */public Iterator Iterate (String queryString);/*** use the HSQL statement with parameters to query data and return Iterator ** @ param queryString * @ param values * @ return */public Iterator Iterate (String queryString, Object [] values ); /*************************************** * ********************************** --------------------- Criteria ----------------------------************************************ ***************************************/ /*** create a session-independent fuse standard pair */public DetachedCriteria createDetachedCriteria (); /*** create a fuse standard bound to the session ** @ return */public Criteria createCriteria (); /*** use the specified number of standard searches ** @ param criteria * @ return */public List FindByCriteria (DetachedCriteria criteria);/*** use the specified search criteria to retrieve data, return some records ** @ param criteria * @ param firstResult * @ param maxResults * @ return */public List FindByCriteria (DetachedCriteria criteria, int firstResult, int maxResults);/*** query criteria using dynamic conditions *** @ param criterion * @ return List * // @ SuppressWarnings ("unchecked") public List FindByCriteria (Criterion... criterion);/*** use the specified search criteria to retrieve data and return the records within the specified range ** @ param criteria * @ return */public Integer getRowCount (DetachedCriteria criteria ); /*** use the specified retrieval standard to retrieve data and return the specified statistics ** @ param criteria * @ param propertyName * @ param StatName * (max, min, avg, sum) * @ return */public Object getStatValue (DetachedCriteria criteria, String propertyName, String StatName);/*** searches for matched objects and associations with tables through a given Object For a large number of users, can they expand according to the quota? ** @ Param entity * @ return List */Public List FindByExample (T entity ); /*************************************** * ********************************** ----------------------- Others ---------------------------------------- **************************************** ***********************************//*** lock the specified instance ** @ param entity * @ param lockMode */public void lock (T entity, lockMode lockMode);/*** force immediately update the buffered data to the database (otherwise, the data is updated only when the transaction is committed) */public vo Id flush ();/*** clear cache ** void */public void clear (); /*************************************** * ********************************** ------------------------ related knowledge when ------------------------------ *** 1. Are the load and get methods of the Session loaded from the database using the given ID? However, the difference between the two shard ** methods is that when the database does not exist in the records corresponding to the ID, the load () method throws an exception and the shard get () method () method returns null ************************************* ***************************************/}
// Universal Hibernate DAO implementation: package com. interval yyy. util. dao;/*** @ filename: BaseHibernateDAO. java */import java. io. serializable; import java. util. collection; import java. util. iterator; import java. util. list; import org. hibernate. criteria; import org. hibernate. lockMode; import org. hibernate. query; import org. hibernate. session; import org. hibernate. criterion. criterion; import org. hibernate. criterion. detachedCriteria; import org. hibernate. criterion. example; import org. hibernate. criterion. matchMode; import org. hibernate. criterion. projections; import com. interval yyy. workflow. pojo. TWfPackage;/*** use Hibernate to implement the universal DAO interface ** @ author yongtree * @ date 2008-3-10 * @ param
* @ Param
*/Public class BaseHibernateDAO
Implements IBaseDAO
{// Keep the object Class type private Class
PersistentClass; private Session session;/*** structure? */@ SuppressWarnings ("unchecked") public BaseHibernateDAO () {// there is an error in the following method, and the real T cannot be obtained. class, which is Object. class // this. persistentClass = GenericsUtils. getSuperClassGenricType (getClass (); // System. out. println (obj. getClass (). getName () ;}@ SuppressWarnings ("unchecked") public BaseHibernateDAO (Class clazz) {this. persistentClass = clazz;}/*** @ param session * the session to set */public void setSession (Session session) {this. session = session;}/*** get the Session object of the current thread ** @ return */protected Session getSession () {System. out. println ("get session"); return HibernateUtil. getCurrentSession ();}/*** get the type of the Persistent Object ** @ return Class of the persistence Class extends */protected Class
GetPersistentClass () {return persistentClass;} @ SuppressWarnings ("unchecked") public T findById (ID id, LockMode lock) {// TODO Auto-generated method stub T entity = (T) getSession (). get (getPersistentClass (), id, lock); if (entity! = Null) {this. flush () ;}return entity ;}@ SuppressWarnings ("unchecked") public T findById (Class c, ID id) {// TODO Auto-generated method stub T entity; entity = (T) getSession (). get (c, id); return entity ;}@ SuppressWarnings ("unchecked") public T findById (ID id) {// TODO Auto-generated method stub T entity = (T) getSession (). get (getPersistentClass (), id); return entity ;}@ SuppressWarnings ("unchecked") public T loadById (ID id) {// TODO Auto-generated method stub T entity = (T) getSession (). load (getPersistentClass (), id); return entity ;}@ SuppressWarnings ("unchecked") public T loadById (Class c, ID id) {// TODO Auto-generated method stub T entity = (T) getSession (). load (c, id); return entity;} @ SuppressWarnings ("unchecked") public T loadById (ID id, LockMode lock) {// TODO Auto-generated method stub T entity = (T) getSession (). load (getPersistentClass (), id, lock); return entity ;}@ SuppressWarnings ("unchecked") public List
LoadAll () {List
List = getSession (). createQuery ("from" + getPersistentClass (). getName ()). list (); return list;} public T saveEntity (T entity) {// TODO Auto-generated method stub getSession (). save (entity); this. flush (); return entity;} public void updateEntity (T entity) {// TODO Auto-generated method stub getSession (). saveOrUpdate (entity); this. flush ();}/*** this implementation class does not implement update and lock operation temporarily */public void updateEntity (T entity, LockMode lock) {// TODO Auto-generated method stub getSession (). saveOrUpdate (entity); this. flush ();} public void saveOrUpdateAll (Collection
Entities) {getSession (). saveOrUpdate (entities); this. flush ();} public void deleteEntity (T entity) {// TODO Auto-generated method stub getSession (). delete (entity); this. flush ();}/*** this implementation does not implement the operation of locking and deleting objects. In the DAO implementation of spring, the actual implementation */public void deleteEntity (T entity, LockMode lock) {// TODO Auto-generated method stub getSession (). delete (entity); this. flush ();} public void deleteEntityById (ID id) {this. deleteEntity (this. loadById (id); this. flush () ;}// this implementation does not implement lock deletion. In spring dao, public void deleteEntityById (ID id, LockMode lock) {this. deleteEntity (this. loadById (id); this. flush ();} public void deleteAll (Collection
Entities) {this. flush (); getSession (). delete (entities);} public void merge (T entity) {getSession (). merge (entity); this. flush () ;}@ SuppressWarnings ("unchecked") public T getEntity (String hsql) {T uniqueResult = (T) getSession (). createQuery (hsql ). uniqueResult (); // TODO Auto-generated method stub return uniqueResult;} @ SuppressWarnings ("unchecked") public List
GetEntities (String hsql) {// TODO Auto-generated method stub List list = getSession (). createQuery (hsql ). list (); return list ;}@ SuppressWarnings ("unchecked") public List
GetEntities (String hql, int start, int number, Object [] values) {// TODO Auto-generated method stub Query query = getSession (). createQuery (hql); for (int I = 0; I <values. length; I ++) {query. setParameter (I, values [I]);} query. setFirstResult (start); query. setMaxResults (number); List list = query. list (); return list ;}@ SuppressWarnings ("unchecked") public List
GetEntities (String hql, int start, int number) {// TODO Auto-generated method stub Query query = getSession (). createQuery (hql); query. setFirstResult (start); query. setMaxResults (number); List list = query. list (); return list ;}@ SuppressWarnings ("unchecked") public List
GetEntities (String hql, Object [] values) {// TODO Auto-generated method stub Query query = getSession (). createQuery (hql); for (int I = 0; I <values. length; I ++) {query. setParameter (I, values [I]);} return query. list () ;}@ SuppressWarnings ("unchecked") public List
FindByNamedQuery (String queryName) {// TODO Auto-generated method stub return getSession (). getNamedQuery (queryName). list () ;}@ SuppressWarnings ("unchecked") public List
FindByNamedQuery (String queryName, Object [] values) {// TODO Auto-generated method stub Query query = getSession (). getNamedQuery (queryName); for (int I = 0; I <values. length; I ++) {query. setParameter (I, values);} return query. list ();}/*** Note: What is the method? If you have set parameters to perform the name query, you must pay attention to the length of paramNames and values when passing the parameters. Must the parameter be in the same region? * // @ SuppressWarnings ("unchecked") public List
FindByNamedQuery (String queryName, String [] paramNames, Object [] values) {// TODO Auto-generated method stub Query query = getSession (). getNamedQuery (queryName); for (int I = 0; I <paramNames. length; I ++) {query. setParameter (paramNames [I], values [I]);} return query. list () ;}@ SuppressWarnings ("unchecked") public Iterator
Iterate (String hql) {// TODO Auto-generated method stub return getSession (). createQuery (hql). iterate () ;}@ SuppressWarnings ("unchecked") public Iterator
Iterate (String hql, Object [] values) {// TODO Auto-generated method stub Query query = getSession (). createQuery (hql); for (int I = 0; I <values. length; I ++) {query. setParameter (I, values [I]);} return query. iterate ();} public DetachedCriteria createDetachedCriteria () {// TODO Auto-generated method stub return DetachedCriteria. forClass (this. persistentClass);} public Criteria createCriteria () {// TODO Auto-generated method stub return this. createDetachedCriteria (). getExecutableCriteria (this. getSession ();}/*** this method has not been verified and cannot be ensured correctly. In spring implementation, it has implemented a public List of hundreds of millions */@ SuppressWarnings ("unchecked ")
FindByCriteria (DetachedCriteria criteria) {// TODO Auto-generated method stub return criteria. encode (this. getSession (). list () ;}@ SuppressWarnings ("unchecked") public List
FindByCriteria (DetachedCriteria criteria, int firstResult, int maxResults) {// TODO Auto-generated method stub return criteria. getExecutableCriteria (this. getSession ()). setFirstResult (firstResult ). setMaxResults (maxResults ). list ();}/*** Dynamic lookup token ** @ param criterion * @ return */public @ SuppressWarnings ("unchecked") List
FindByCriteria (Criterion... criterion) {Criteria crit = getSession (). createCriteria (getPersistentClass (); for (Criterion c: criterion) {if (c! = Null) {crit. add (c) ;}} List list = crit. list (); return list ;}@ SuppressWarnings ("unchecked") public Integer getRowCount (DetachedCriteria criteria) {// TODO Auto-generated method stub criteria. setProjection (Projections. rowCount (); List list = this. findByCriteria (criteria, 0, 1); return (Integer) list. get (0) ;}@ SuppressWarnings ("unchecked") public Object getStatValue (DetachedCriteria criteria, String propertyName, String StatName) {// TODO Auto-generated method stub if (StatName. toLowerCase (). equals ("max") criteria. setProjection (Projections. max (propertyName); else if (StatName. toLowerCase (). equals ("min") criteria. setProjection (Projections. min (propertyName); else if (StatName. toLowerCase (). equals ("avg") criteria. setProjection (Projections. avg (propertyName); else if (StatName. toLowerCase (). equals ("sum") criteria. setProjection (Projections. sum (propertyName); else return null; List list = this. findByCriteria (criteria, 0, 1); return list. get (0) ;}@ SuppressWarnings ("unchecked") public List
FindByExample (T exampleInstance) {// TODO Auto-generated method stub Criteria crit = getSession (). createCriteria (getPersistentClass (); Example example = Example. create (exampleInstance); example. ignoreCase (). enableLike (MatchMode. ANYWHERE); // ignore case sensitivity and perform fuzzy comparison example. excludeZeroes (); // if the value of exampleInstance is 0, add it to crit in the query. add (example); return crit. list ();} public void lock (T entity, LockMode lockMode) {// TODO Auto-generated method stub getSession (). lock (entity, lockMode);} public void flush () {// TODO Auto-generated method stub getSession (). flush ();} public void clear () {// TODO Auto-generated method stub getSession (). clear ();}}
Summary: This chapter mainly discusses when to use generics.