Under new Java features

Source: Internet
Author: User

    • Generic type
Why generics are required and what are generics? when the object type data is saved to the collection, it loses its type, becomes the object type when it is removed, and the object type needs to be strongly reversed to the lost data type, which can lead to the programmer's misoperation problem, which brings security! Generics are forcing a collection to hold only one data type, so there is no problem with element data type Loss!!
Package generics; import Java.util.arraylist;import Java.util.hashmap;import Java.util.iterator;import Java.util.linkedhashmap;import java.util.list;import java.util.map;import Java.util.map.entry;import java.util.Set Import org.junit.test;public class generic generic cause {@Testpublic void Test () {//Programmer write code, forget the type of conversion, but the project code is not an error/*arraylist Al = new ArrayList (); Al.add ("123"); Integer num = (integer) al.get (0);//encoding without error System.out.println (num); */list<string > list1 = new arraylist<string> ();//declares that the collection can handle only String data List1.add ("1"), List1.add ("2"), List1.add ("3"); Terator<string> it = List1.iterator (); while (It.hasnext ()) {String value = It.next (); System.out.println (value);} for (String num:list1) {System.out.println (num);}} @Testpublic void Test2 () {//hashmap may cause the order to be taken and the order of the deposit to be inconsistent, we can choose to use the linkedhashmap//shopping cart to//map<integer, string> Map = new Linkedhashmap<integer, string> (); Map<integer, string> map = new Hashmap<integer, string> (), Map.put (1, "AA"), Map.put (2, "BB"), Map.put (3, "CC"); Map.put (4, "DD"); Map.put (5, "ee"); Map.put (6, "FF");//set specifically takes out the step-outs Set<entry<integer, string>> set = Map.entryset (); Iterator<entry<integer, string>> it = Set.iterator (); while (It.hasnext ()) {Entry< Integer,string> e = It.next (); Integer key = E.getkey (); String value = E.getvalue (); System.out.println ("Key:" +key+ "value:" + value);} Enhanced for loop out element for (entry<integer,string> E:map.entryset ()) {Integer key = E.getkey (); String value = E.getvalue (); System.out.println ("Key:" +key+ "value:" + value);}}}
Package generics; Import org.junit.test;//custom generic method (Custom generic class Support Unit test) public class custom generic <T> {//class above declares a generic action on the entire class, But does not function on the static method @testpublic void Testa () {//string b = A ("AAA");//system.out.println (b);} Declare first, then use public <E,K>  t A (t T, E e,k K) {//The essence of generics is to parameterize the data type System.out.println (t); return T;} The essence of declaring, then using public T A (t) {//generics--is to parameterize the data type System.out.println (t); return T;} Writes a generic method that implements the interchange of the specified array element public static <T> void Change (t[] arr1, int m, int n) {T temp = arr1[m];arr1[m] = arr1[n];arr1 [n] = temp;} Write a generic method that reverses the array element public  void Changall (t[] arr) {int start = 0;int end = arr.length-1;for (int i=end, j = start; I > J; I--, j + +  ) {T temp = arr[i];arr[i] = arr[j];arr[j] = temp;}} @Testpublic void Testchange () {custom generics <String> zdy = new Custom generics <String> (); string[] Arr  = {"1", "2", "3", "4", "5"};zdy.changall (arr); for (String S:arr) System.out.println (s);}}

Package generics, Import Org.junit.test;public class  <t,e>{//Custom generic class, parameters valid within the entire class public T Gett (T t) {return t;} @Testpublic void Test () {generic class <String,Integer> FXL = new generic class <string, integer> (); System.out.println (Fxl.gett ("ADASD"));}}

    • Reflection
what is reflection and why does it need reflection?reflection is a technique used by the Java framework to get its properties, methods, and constructors based on the user-supplied classpath and name. This allows you to invoke a method and assign a value to a property by using the reflection Operation class and class instance!!
Package Reflection Reflect;import Java.io.inputstream;import Java.util.list;public class Person {public String address;public static string sdept;private int age;private string name;private List list;public person () {System.out.println (" The person without a parameter constructor is executed ");} Private person (List list) {this.list = list; SYSTEM.OUT.PRINTLN ("list private constructor");} public person (int age, String name) {this.age = Age;this.name = name; System.out.println ("Age:" + Age + ", Name:" + name);} ---------------------------------------------public void Eat () {System.out.println ("eat");} public void Run (String name) {System.out.println ("name:" + name); System.out.println ("Run");} Public class[] Execute (String name, List list) {System.out.println ("executed Excute method"); return new Class[]{string.class};} private void Excute2 (InputStream in) {System.out.println ("performed Excute2 method"); System.out.println (in);} public static void excute3 (int num) {System.out.println ("performed Excute3 method"); SYSTEM.OUT.PRINTLN (num);} public static void Main (string[] args) {System.out.println ("MAin ");} public void Intarr (int[] arr) {for (int i:arr) {System.out.print (i+ "");}} public void Stringarr (string[] arr) {for (String S:arr) {System.out.print (S + "");}}}

Package Reflection Reflect;import org.junit.test;/* * Load Class * Reflection: * 0. Create an XML configuration file * 1. Read configuration information for the configuration file (usually XML) * 2. Load the configuration file class * 3. Dissect the properties of the loaded class (encapsulated Data), construct method (Create Object), method (perform a function) */public class Demo {@Testpublic void Test () throws classnotfoundexception{//Load class//method One: Class Clazz = Class.forName ("Myday01.src. Reflection Reflect.person");//Method Two class clazz1 = new Person (). GetClass ();//Method three Class clazz2 = Person.class;}}

Package Reflector Reflect;import Java.util.list;import java.lang.reflect.constructor;import Java.util.arraylist;import org.junit.test;/* * Reflection class constructor, creating object of Class */public class Demo2 {@Testpublic void Test () throws Exception {//Reflection parameterless constructor, Pulic Pers On () {}//load Class clazz = Class.forName ("reflection reflect. Person ");//Gets the constructor constructor C = Clazz.getconstructor (null);//The specified parameterless constructor//creates an object from the constructor. Person P = (person) c.newinstance ( NULL);} A constructor that reflects a parameter @testpublic void Test1 () throws Exception {Class clazz = Class.forName ("reflection reflect. Person "); Constructor C = clazz.getconstructor (Int.class, String.class); Person P = (person) c.newinstance ("Li");} Reflecting the private constructor, reflection is able to do external access to the private constructor @testpublic void Test2 () throws Exception {Class clazz = Class.forName ("reflection reflect. Person ");//GetConstructor can only get the public type of construction method constructor C =//clazz.getconstructor (List.class); Constructor C = clazz.getdeclaredconstructor (List.class); c.setaccessible (true);//violent reflection, allowing private constructors to externally access the person P = ( person) c.newinstance (new ArrayList ());} The simplest way to create an object (and the first method is aLike, the default call to the parameterless constructor) @Testpublic void Test3 () throws Exception{class Clazz = Class.forName ("reflection reflect. Person "); Person P = (person) clazz.newinstance ();}}

Package Reflector Reflect;import Java.util.list;import java.io.fileinputstream;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.lang.reflect.method;import Java.util.arraylist;import org.junit.Test;// Method of reflection class public class Demo5 reflection method {@Testpublic void Test () throws Exception{person p = new person (); Class clazz = Class.forName ("reflection reflect. Person "); Method m = Clazz.getmethod ("eat", null);//Get Method name eat, specify its parameter is Nullm.invoke (P, NULL);//object P method execution, parameter is NULL//reflection common type method m2 = Clazz.getmethod ("Run", string.class);//Gets the method name of the method named run, specifying its parameter type is String type M2.invoke (P, "LJ"),//p object executes this method, the parameter name is "LJ"// Reflection String and List type method m3 = Clazz.getmethod ("Execute", String.class, List.class); M3.invoke (P, "LJ", New ArrayList ());// Reflection InputStream Type Method m4 = Clazz.getdeclaredmethod ("Excute2", Inputstream.class); m4.setaccessible (true); M4.invoke ( P, New FileInputStream ("D://a.txt"));//Reflection static method of class Method M5 = Clazz.getmethod ("Excute3", Int.class); M5.invoke (null, 10) ;//static objects do not require objects at call time, other parameters and reflection common methods are not different//reflection Main Method mm = Clazz. GetMethod ("main", String[].class); Mm.invoke (null, (Object) New string[]{"123"});// JDK1.4 does not have a variable parameter (pass multiple parameters are implemented in the form of an array),//jdk1.5 in order to be compatible with the 1.4 version, the array class parameters in the reflection will be split into the number of elements of the group of parameters to pass,//reflection array type data, Can be cast to Object type first to do//reflection integer Array Method marr = Clazz.getmethod ("Intarr", Int[].class); Marr.invoke (P, (Object) New int[]{ 1,2,3,4,5});//int array type tested, not strong turn is also possible//reflection character Array Method INTRR = Clazz.getmethod ("Stringarr", String[].class); Intrr.invoke ( P, (Object) New string[]{"1", "2"});//string array type must be strong}}

Package Reflector Reflect;import Java.util.list;import java.lang.reflect.field;import Java.util.arraylist;import Org.junit.test;public class Demo6 reflection field {@Testpublic void Test () throws Exception{person p = new person (); Class clazz = Class.forName ("reflection reflect. Person ");//reflection normal field F = Clazz.getfield (" Address "); object FV = F.get (P);//Gets the value of the Address field to the P object if (F.gettype (). Equals ( String.class)) {F.set (P, "Chongqing"); String address = (string) f.get (p); SYSTEM.OUT.PRINTLN (address);} The private field is reflected in fields FF = Clazz.getdeclaredfield ("Age"), ff.setaccessible (True), if (Ff.gettype (). Equals (Int.class)) { Ff.set (p); int ffvalue = (Integer) ff.get (p); System.out.println (Ffvalue);} Reflection ListField FL = Clazz.getdeclaredfield ("list"), Fl.setaccessible (True), if (Fl.gettype (). Equals (List.class)) {List Alist = new ArrayList (); Alist.add (1); Alist.add (2); Alist.add (3); Alist.add (4); Fl.set (P, alist); List List = (list) Fl.get (p), for (Object i:alist) System.out.print ((Integer) i + "");} Reflection static fields Field FS = Clazz.getfield ("sdept"); if (Fs.gettype (). EQuals (String.class)) {Fs.set (null, "\ n Computer Engineering Test Center"); String FSV = (string) fs.get (null); System.out.println (FSV);}}}
    • Introspection
what is introspection and what is the use of introspection? introspection is also a technique that is often used in framing. Personal Understanding: Introspection is a technical complement to reflective properties, and reflection is too cumbersome to manipulate properties, so there's introspection.
Package Introspection Introspector;import Java.beans.beaninfo;import Java.beans.introspector;import Java.beans.propertydescriptor;import Java.lang.reflect.method;import org.junit.test;//using the Introspection API to manipulate bean properties public Class Demo {//Get all the attributes within the Bean @testpublic void Test1 () throws exception{///on the Java Bean for all its properties, exposed methods, and events. BeanInfo bin = introspector.getbeaninfo (Person.class, object.class);//Gets the person property, methods, and events, excluding properties and methods inherited by class above the Object parent class and events Get the property descriptor of the person class propertydescriptor[] Pros = bin.getpropertydescriptors ();//Show all attributes in the Person-object inheritance chain for ( PropertyDescriptor Pro:pros) {System.out.println (Pro.getname ());} Output A,age,class,name,password Five attributes, the class attribute is derived from the inherited parent class object, and the other attributes are judged based on the Get method (which must have a return value)}//The specified properties of the operation Bean: Age@testpublic void Test2 () throws exception{person P = new person ();//Get property descriptor PropertyDescriptor PD = new PropertyDescriptor ("Age", Perso N.class);//Assign a value to the Age attribute method MPD = Pd.getwritemethod (); Mpd.invoke (P, 20); Method execution//Gets the value of the Age property Method Mpd2 = Pd.getreadmethod (); int mpd2v = (Integer) mpd2.invoke (p, NULL); System.out.prinTLN (MPD2V);} Gets the type of the property of the current Operation @testpublic Void Test3 () throws exception{propertydescriptor pd = new PropertyDescriptor ("Age", Person.class);//Gets the description of the attribute type to the property descriptor if (Pd.getpropertytype (). Equals (Int.class)) {System.out.println ( Pd.getpropertytype ());}}}

Package Introspection introspector;//introspection: What is JavaBean (the following form is called JavaBean) public class Person {private String name;//No Get/set method is called a field, There is a Get/set method called property private string Password;private int age;public string getName () {return name;} public void SetName (String name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} public int getage () {return age;} public void Setage (int.) {this.age = age;} The field is not declared, but there is a Set/get method, which is also an attribute//below is also a property of public void SetA () {}//A total of 5 properties, a GetClass property method is integrated from Object public String Geta () { return "AA";}}

Use of the Beanutils tool class:
Package Beanutils;import Java.lang.reflect.invocationtargetexception;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.date;import Java.util.hashmap;import Java.util.Map;import Org.apache.commons.beanutils.beanutils;import Org.apache.commons.beanutils.conversionexception;import Org.apache.commons.beanutils.convertutils;import Org.apache.commons.beanutils.converter;import Org.apache.commons.beanutils.locale.converters.datelocaleconverter;import Org.junit.test;//beanutil Operation Bean Properties ( Third-party jar package) public class Beanutils Operation Bean Property {//Using Beanutils action Bean property @testpublic void Test () throws Illegalaccessexception, Invocationtargetexception{person p = new person (); Beanutils.setproperty (P, "name", "LJ"); System.out.println (P.getname ());} Beanutils's convenience embodies @testpublic void Test2 () throws Illegalaccessexception, invocationtargetexception{// The data submitted by the form is a string of type string age= "23"; String name= "Lijun"; String password = "SDASD"; Person p = new person (); Beanutils.setproperty (P, "age", age);//Type AutomaticConversion (only 8 basic types supported) Beanutils.setproperty (p, "name", name); Beanutils.setproperty (P, "password", password); System.out.println (P.getage () + "," +p.getname () + "," +p.getpassword ());} Registration and use of converters (string conversion to date type) @Testpublic void Test3 () throws Illegalaccessexception, invocationtargetexception{ String birthday= "1990-07-09";//date type conversion/*convertutils.register (new Converter () {public Object convert (Class type, Object value) {if (value==null) return null;if (! ( Value instanceof String) {throw new Conversionexception ("only supports string-type conversions");} String str= (String) value;if (Str.trim (). Equals ("")) return null; SimpleDateFormat df=new SimpleDateFormat ("Yyyy-mm-dd", locale.us); try {return df.parse (str);} catch (ParseException e) {throw new RuntimeException (e);//exception chain, E can not be lost//There is an exception must be thrown, notify the previous layer of the program. Otherwise, the previous program will not be able to know whether this program is wrong, and continue to execute}}}, Date.class); */convertutils.register (new Datelocaleconverter (), date.class); Person p = new person (); Beanutils.setproperty (P, "Birthday", birthday);//registers the date type converter System.out.println (P.getbirthday (). toLocaleString ()) ;} //beanutils Auto-populate data @testpublic void Test4 () throws Illegalaccessexception, invocationtargetexception{//client-submitted data map map = New HashMap (); Map.put ("name", "Li June"), Map.put ("Birthday", "1999-09-09"), Map.put ("Password", "Sadaqwe"); Map.put ("Age" , "123456");//Register Date data type conversion convertutils.register (new Converter () {@Overridepublic object convert (Class type, object Value) {//TODO auto-generated method stubif (! ( Value instanceof String)) throw new Conversionexception ("Can only convert String type data"); String str = (string) value;if ("". Equals (Str.trim ())) return null;if (value==null) return null;//conversion function SimpleDateFormat DF = new SimpleDateFormat ("Yyyy-mm-dd"); try {return df.parse (str);} catch (ParseException e) {//TODO auto-generated catch bl Ockthrow new RuntimeException (e); Df.format (date) goes from date to string,parse from string to date}, Date.class);//beanutils autofill data person p = new person (); Beanutils.populate (P, map); System.out.println (P.getname () +p.getpassword () +p.getage () +p.getbirthday (). toLocaleString ());}}

Package Beanutils;import java.util.date;//Introspection: What is JavaBean (the following form is called JavaBean) public class Person {private String name; There is no Get/set method called field, which has the Get/set method called property private string password;private int age;private Date birthday;public string GetName () { return name; public void SetName (String name) {this.name = name;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} public int getage () {return age;} public void Setage (int.) {this.age = age;} The field is not declared, but there is a Set/get method, which is also an attribute//below is also a property of public void SetA () {}//A total of 5 properties, a GetClass property method is integrated from Object public String Geta () { return "AA";} Public Date Getbirthday () {return birthday;} public void Setbirthday (Date birthday) {this.birthday = birthday;}}






Under new Java features

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.