The use of generics guarantees that the returned object type is correct;
Packagecom.stono.gentest;Importjava.util.ArrayList;Importjava.util.List; Public classStoryteller { Public Static voidMain (string[] args) {List<Minstrel> story = storytemplate.getstory ("select", NewStoryi<minstrel>() {@Override PublicMinstrel Gethero (String name) {return NewMinstrel (name); } }, 1); for(Minstrel minstrel:story) {System.out.println (Minstrel.getname ()); } }}classMinstrel {PrivateString name; PublicMinstrel (String name) { This. Name =name; } PublicString GetName () {returnname; }}//================== Below is the pseudo-frame part, the above is the pseudo-client part; =====================//The template method creates generic objects according to the rules of the interface, and the logic of assembling them according to the conditions does not need to be written by the client;classStorytemplate { Public Static<T> list<t> getstory (String str, storyi<t>T, Object ... o) {List<T> list =NewArraylist<t>(); if("select". Equals (str)) {//a Query method similar to JDBC;String[] STRs = {"A", "B" }; for(String string:strs) {List.add (T.gethero (string)); } } returnlist; }}InterfaceStoryi<t>{T Gethero (String name);//passing in a parameter string guarantees that a generic object is returned, and the assembly logic is implemented by the client;}
Java generics for similar applications in spring JDBC template