Generic Erase Reflection Auto-assembly

Source: Internet
Author: User

1. Generic Erase

 PackageCn.itcast.demo;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;Importjava.util.List; Public classDemo1 { Public Static voidMain (string[] args)throwsSecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, invocationtargetexception {//Define a list<integer>list<integer> list =NewArraylist<integer>(); //Add a string "abc"//List.add ("abc"); //problem solving, using reflection//1. Get the list class. Class Clazz =List.getclass (); //2. Use Clazz to get the Add method.Method Addmethod=clazz.getmethod ("Add", Object.class); //3. Call the Add method, adding "abc".Addmethod.invoke (list,"ABC");    SYSTEM.OUT.PRINTLN (list); }}

2. Four ways to get objects.
1.new
2. Reflection
3.IO Stream (Object stream)----Note the need to implement serializable
4.clone ()---you need to override the Clone () method in the class to implement the Cloneable interface.

 PackageCn.itcast.demo;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.io.ObjectInputStream;ImportJava.io.ObjectOutputStream;Importorg.junit.Test;//Get Object Public classDemo2 {//1.new@Test Public voidfun1 () {person P=NewPerson (); }    //using Reflection@Test Public voidFun2 ()throwsclassnotfoundexception, Instantiationexception, illegalaccessexception {Class C= Class.forName ("Cn.itcast.demo.Person");    C.newinstance (); }    //3. Use IO stream.@Test Public voidFUN3 ()throwsFileNotFoundException, IOException {//writes an object to the Object.txt file.Person p =NewPerson (); P.setname ("Tom"); P.setsex ("Male"); P.setaddress (Beijing); //in Java If you are describing a path that uses two \ \, you can also use one/. File File=NewFile ("D:/java0106/workspace/day02/src/object.txt"); // //Absolute Path//relative Path//file File=new file ("Src/object.txt"); //gets the classpath path in development. Gets the root directory of our classpath path. Then if the file exists in the bin, you can write the path directly behind it.//String Path = Demo2.class.getResource ("/object.txt"). GetPath (); //file File=new file (path); //System.out.println (File.exists ());writeobjecttofile (p, file); } @Test Public voidFun4 ()throwsFileNotFoundException, IOException, classnotfoundexception {file file=NewFile ("D:/java0106/workspace/day02/src/object.txt"); Person P=(person) readobjectfromfile (file);    SYSTEM.OUT.PRINTLN (P); }    //reading an object from a file    PrivateObject readobjectfromfile (file file)throwsFileNotFoundException, IOException, classnotfoundexception {objectinputstream ois=NewObjectInputStream (Newfileinputstream (file)); Object obj=Ois.readobject ();        Ois.close (); returnobj; }    //actions to write an object to a file    Private voidwriteobjecttofile (Object obj, file file)throwsFileNotFoundException, IOException {objectoutputstream oos=NewObjectOutputStream (Newfileoutputstream (file));        Oos.writeobject (obj);        Oos.flush ();    Oos.close (); }    //using clones@Test Public voidFun5 ()throwsclonenotsupportedexception {person P=NewPerson (); P.setname ("Tom"); P.setsex ("Male"); P.setaddress (Beijing); Person pp= (person) p.clone ();//get a copy of a P objectSystem.out.println (PP); }}

2

 PackageCn.itcast.demo;Importjava.io.Serializable; Public classPersonImplementscloneable{//implements Serializable {//private static final long serialversionuid = 1L;    PrivateString name; PrivateString sex; PrivateString address;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getsex () {returnsex; }     Public voidsetsex (String sex) { This. Sex =sex; }     PublicString getaddress () {returnaddress; }     Public voidsetaddress (String address) { This. Address =address; } @Override PublicString toString () {return"Person [name=" + name + ", sex=" + Sex + ", address=" +Address+ "]"; } @Override PublicObject Clone ()throwsclonenotsupportedexception {return Super. Clone (); }}

3. Automatic assembly operation.
Create a Map collection.
Map.put ("name", "Tom");
Map.put ("Sex", "male");
Map.put ("Address", "Beijing");

Person class.
Class person{

private String name;
Private String sex;
Private String address;

Get/set method.
}

Requires that, using reflection, the key value in the Map collection is assigned to the property of the person class using the value of key, which is the same as the property name in the People class.

Use the method class operation without using the field class.

 PackageCn.itcast.demo;ImportJava.lang.reflect.Field;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Set;Importorg.junit.Test; Public classDemo3 { Public Static voidMain (string[] args)throwsSecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, InvocationTarg etexception {Map<string, string> map =NewHashmap<string, string>(); Map.put ("Name", "Tom"); Map.put ("Sex", "male"); Map.put ("Address", "Beijing"); Person P=NewPerson (); //1. Get all keys in the collectionset<string> keys =Map.keyset (); //2. Get the attributes in all the person classes.Class Clazz =P.getclass (); Field[] Fields= Clazz.getdeclaredfields ();//property is Private//3. Traverse the property to determine if the keys contain these attributes.         for(Field field:fields) {//gets the property name.String FieldName =Field.getname (); if(Keys.contains (fieldName)) {//The key in the map collection contains such a property name.                Then you need to call this property's corresponding set method to assign the value of the key corresponding to the operation. //1. Get ValueString value =Map.get (fieldName); //2. Get the Set method corresponding to the attributeMethod Setmethod =Clazz.getmethod (Getsetmethodname (fieldName), String.class); //3. Call the method to assign the value.Setmethod.invoke (p, value);    }} System.out.println (P); }     Public Staticstring Getsetmethodname (string param) {return"Set" + (Char) (Param.charat (0)-+) + param.substring (1); } @Test Public voidFun () {//' n '---->nSystem.out.println ((Char) (' N '-32)); }}

Generic Erase Reflection Auto-assembly

Related Article

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.