Java reflection application and Java reflection Application

Source: Internet
Author: User

Java reflection application and Java reflection Application

 

Package com. zheges; import java. util. date; public class Customer {// JavaBean object private String name; private int password; public String present = "God"; private Date date; @ Overridepublic String toString () {return "Customer [name =" + name + ", password =" + password + ", present =" + present + ", date =" + date + "]";} public String getPresent () {return present;} public void setPresent (String present) {this. present = present;} public String getName () {return name;} public Date getDate () {return date;} public void setDate (Date date) {this. date = date;} public void setName (String name) {this. name = name;} public int getPassword () {return password;} public void setPassword (int password) {this. password = password;} public String getAB () {return "AB ";}}

 

Package com. zheges; import static org. junit. assert. assertEquals; // statically import all static methods of Assert import java. lang. reflect. field; import org. junit. before; import org. junit. test;/*** Project name: Reflection * Class Name: FirDemo * class description: Basic Application of Reflection * created by: ZHe * created at: 5:01:43, January 1, August 29, 2015 * modified: ZHe * modification time: August 29, 2015 5:01:43 */public class FirDemo {private Class <?> Clazz; // class bytecode private Customer customer Customer = new Customer ();/*** 1. load the class and obtain the byte code * @ throws ClassNotFoundException */@ Beforepublic void getClassLoader () throws ClassNotFoundException {// 1. use the static method of Class to load clazz = Class. forName ("com. zheges. customer "); // note: the full name of the class must be used here // 2. obtain its bytecode clazz = new Customer () through a class object (). getClass (); // 3. obtain clazz = Customer through the static attribute of the class. class; assertEquals ("com. zheges. customer ", clazz. getName ());}/** * 2. Obtain the fields of the class (Note: The attributes are determined by getter !) * @ Throws SecurityException * @ throws NoSuchFieldException * @ throws handler */@ Testpublic void getClassProperties () throws NoSuchFieldException, SecurityException, exceptions, writable {// 1. obtain the private Field and its type field Field = clazz. getDeclaredField ("name"); Class <?> Type = field. getType (); assertEquals (String. class, type); // 2. obtain the public Field and its type Field field1 = clazz. getField ("present"); Class <?> Type1 = field1.getType (); assertEquals (String. class, type1); // 3. true if this object is the same as the obj argument; false otherwise. assertEquals (true, field. equals (clazz. getDeclaredField ("name"); // 4. set the field value for this field on an object. setAccessible (true); // This field is private and must be set to setAccessiblefield. set (customer, "ZheGes"); field1.set (customer, "Nor"); assertEquals (customer. getName (), "ZheGes"); assertEquals (customer. getPresent (), "Nor"); // 5. obtains the value of this field assertEquals (field. get (customer), "ZheGes"); // The premise is that the private variable sets AccessibleassertEquals (field1.get (customer), "Nor ");}}

 

Package com. zheges; import java. beans. beanInfo; import java. beans. introspectionException; import java. beans. introspector; import java. beans. propertyDescriptor; import java. lang. reflect. invocationTargetException; import java. lang. reflect. method; import static org. junit. assert. *; import org. junit. ignore; import org. junit. test;/*** Project name: Reflection * Class Name: SecDemo * class description: Reflection advanced application: inner province * created by: ZHe * created at: PM, January 1, August 29, 2015: 02 * modifier: ZHe * modification time: 5:03:02 on April 9, August 29, 2015 */public class SecDemo {// Introspection: access the javabean technology through reflection // JavaBean: 1. constructor with or without parameters 2. the attribute must be private (the number of properties is determined by the get number, not by the field !) 3. provide standard getter and setter // 1. print all attributes of the Customer (including the attributes of the Object)/* result: AB ----- Customer getterclass ---- Object getter, getClass ----> This method inherits the datenamepasswordpresent */@ Ignorepublic void getProperties () throws IntrospectionException {BeanInfo beanInfo = Introspector. getBeanInfo (Customer. class); PropertyDescriptor [] propertyDescriptors = beanInfo. getPropertyDescriptors (); for (PropertyDescriptor propertyDescriptor: propertyDescriptors) {System. out. println (propertyDescriptor. getName () ;}// 2. print all attributes of the Customer (excluding the attributes of the Object) @ Ignorepublic void getOwnProperties () throws IntrospectionException {BeanInfo beanInfo = Introspector. getBeanInfo (Customer. class, Object. class); PropertyDescriptor [] propertyDescriptors = beanInfo. getPropertyDescriptors (); for (PropertyDescriptor propertyDescriptor: propertyDescriptors) {System. out. println (propertyDescriptor. getName () ;}// 3. operation of the specified attribute @ Testpublic void actProperty () throws IntrospectionException, exceptions, exceptions, InvocationTargetException {Customer customer Customer = new Customer (); PropertyDescriptor propertyDescriptor = new PropertyDescriptor ("name", Customer. class); Method method = propertyDescriptor. getWriteMethod (); method. invoke (customer, "zheGes"); Method method2 = propertyDescriptor. getReadMethod (); System. out. println (method2.invoke (customer, null);} // 4. obtain the type of the current operation attribute @ Ignorepublic void getPropertyType () throws IntrospectionException {PropertyDescriptor propertyDescriptor = new PropertyDescriptor ("name", Customer. class); assertEquals (String. class, propertyDescriptor. getPropertyType ());}}

 

Package com. zheges; import static org. junit. assert. assertTrue; 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; impo Rt org. apache. commons. beanutils. converter; import org. apache. commons. beanutils. locale. converters. dateLocaleConverter; import org. junit. ignore; import org. junit. test;/*** Project name: Reflection * Class Name: ThrDemo * class description: advanced application of Reflection 2: BeanUtils * created by: ZHe * Creation Time: august 29, 2015 5:50:20 * modifier: ZHe * modification time: August 29, 2015 5:50:20 */public class ThrDemo {private Customer customer = new Customer (); // 1. beanUtils operation attribute @ Ignorepublic void ActProperty () throws IllegalAccessException, InvocationTargetException, Exception {BeanUtils. setProperty (customer, "name", "ZHeGes"); BeanUtils. setProperty (customer, "password", "404"); // String to int occurs, but this conversion only supports eight basic types! System. out. println (BeanUtils. getProperty (customer, "name") + "" + BeanUtils. getProperty (customer, "password");} // 2. for non-basic conversions, register the Converter @ Ignorepublic void registConver () throws Exception {// register a date Converter, Converter interface, and implement ConvertUtils using an anonymous internal class. register (new Converter () {@ Overridepublic Object convert (Class type, Object value) {if (null = value) {return null;} if (! (Value instanceof String) {throw new ConversionException ("only String type conversion supported");} String str = (String) value; simpleDateFormat simpleDateFormat = new SimpleDateFormat ("yyyy-MM-dd"); try {return simpleDateFormat. parse (str);} catch (ParseException e) {throw new RuntimeException (e); // The exception chain cannot be broken !}}}, Date. class); BeanUtils. setProperty (customer, "date", "1992-3-18"); // The property's value, converted to a StringSystem. out. println (BeanUtils. getProperty (customer, "date"); System. out. println (customer. getDate (). toLocaleString ();} // 3. use the date converter @ Ignorepublic void registConver2 () throws Exception {ConvertUtils. register (new DateLocaleConverter (), Date. class); BeanUtils. setProperty (customer, "date ", "1992-3-18"); System. out. println (customer. getDate (). toLocaleString ();} // 4. use BeanUtils to populate the Map object with JavaBean @ Ignorepublic void usePopulate () throws Exception {Map map = new HashMap <> (); map. put ("name", "ZheGes"); map. put ("password", "123"); map. put ("date", "1992-2-1"); // date converter ConvertUtils. register (new DateLocaleConverter (), Date. class); BeanUtils. populate (customer, map); System. out. println (customer) ;}@ Testpub Lic void test () {String str = "hell"; String str1 = str; str = "wofl"; System. out. println (str + "" + str1) ;}@ Ignorepublic void test2 () {Class <String> t1 = String. class; // Class <String> t2 = Date. class; false: The type constraint is added. It must be a String-like bytecode; otherwise, an error is returned! Class t3 = String. class; assertTrue (t1 = t3 );}}

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.