Java_ Reflection _ and its simple application (2016-11-16)

Source: Internet
Author: User
Tags array length modifiers throw exception

Not much to say directly on the code

Interface:

Package bean;/** * User Interface */public interface user {public String getName ();p ublic void SetName (String name);}

Parent class:

Package bean;/** * Man as Userimpl's parent class */public class Person {private string Name;public string City;public string GetName () { return name; public void SetName (String name) {this.name = name;} Public String getcity () {return city;} public void Setcity (String city) {this.city = city;} @Overridepublic String toString () {return ' person [name= + name + ', city= ' + City + '] ";}}

Implementation class:

Package bean;/** * User Implementation class * The current class does not implement the method in user, which is implemented by the parent class. */public class Userimpl extends person implements user{/** * User name */private string username;/** * Password */private string PASSW ord;/** * is rich */boolean isrich;/** * Age */protected int age;/** * Information */public stringbuffer info;public UserImpl () {Super ( );} Public Userimpl (String userName) {super (); this.username = UserName;} @Overridepublic String toString () {return "Userimpl [username=" + UserName + ", password=" + password+ ", isrich=" + isric H + ", age=" + Age + ", info=" + info+ "]";} Public String GetUserName () {return userName;} public void Setusername (String userName) {this.username = UserName;} Public String GetPassword () {return Password;} public void SetPassword (String password) {password = password;} public Boolean Isrich () {return isrich;} public void Setrich (Boolean Isrich) {This.isrich = Isrich;} public int getage () {return age;} public void Setage (int.) {this.age = age;} Public StringBuffer GetInfo () {return info;} public void SetInfo (striNgbuffer info) {this.info = info;}} 

Factory Interface:

Package Bean;public interface Factory {<t> T getbean (String name, Class<t> requiredtype) throws Exception;}

Factory:

Package Bean;public class Factoryimpl  implements factory{/** * Get instance * @param Class1 * @return * @throws Exception  */@SuppressWarnings ("unchecked") @Overridepublic  <T> T getbean (String name, class<t> requiredtype) Throws Exception {Object object = null;try {class<?> clazz = class.forname (name); object = Clazz.newinstance ();} CATC H (classnotfoundexception e) {e.printstacktrace ();} catch (Instantiationexception e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace ();} If obj is an instance of this class, this method returns True. if (requiredtype! = null &&!requiredtype.isinstance (object)) {throw new Exception ("Class different, throw exception");} Return (T) object;}}

Test class:

Package Bean;import Java.lang.reflect.array;import Java.lang.reflect.constructor;import Java.lang.reflect.Field; Import Java.lang.reflect.invocationhandler;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;import Java.lang.reflect.modifier;import Java.lang.reflect.proxy;import Java.util.arraylist;import Java.util.list;import Org.junit.test;public class Reflecttest {private String className = " Bean. Userimpl ";/** * Gets the instantiated class object */@Testpublic void test01 () throws classnotfoundexception {class<?> class1 = null; Class<?> class2 = null; Class<?> CLASS3 = null;//The first way: Class1 = Class.forName (ClassName);//generally take this form//The second way: in Java each type has a Class attribute. Class2 = userimpl.class;//The Third way: Any Java object in the Java language has a getclass method class3 = new Userimpl (). GetClass (); System.out.println ("class name" + Class1.getname ()); System.out.println ("class name" + Class2.getname ()); System.out.println ("class name" + Class3.getname ());//The usage of the number. T is to fix the type, but not fixed//list<?> userlist = new ArrayList<> ();} /** * Get the class later we'll create its object */@Testpublic void test02 () throws ClassNotFoundException, Instantiationexception, Illegalaccessexception {class<?> clazz = Class.forName (className);//Create a new instance of the class represented by this class object Object object = Clazz.newinstance (); Call the parameterless constructor method. System.out.println (Clazz); System.out.println (object);} /** * Gets the parent class of the object inheritance and implements the interface * @throws classnotfoundexception */@Testpublic void test03 () throws ClassNotFoundException {class& lt;? > clazz = Class.forName (className);//Direct parent class class<?> superclass = Clazz.getsuperclass (); System.out.println ("Clazz's immediate parent class is:" + superclass.getname ());//calzz's parent class is: Bean. person//all interfaces class<?>[] interfaces = Clazz.getinterfaces (); SYSTEM.OUT.PRINTLN ("Clazz implemented interfaces are:"); for (int i = 0; i < interfaces.length; i++) {System.out.println ((i + 1) + ":" + inte Rfaces[i].getname ());} The interfaces implemented by CLAZZ are://1:bean. user}/** * Get all properties of a class * @throws classnotfoundexception */@Testpublic void test04 () throws ClassNotFoundException {class& lt;? > clazz = Class.fornamE (className); System.out.println ("=============== Current class attribute field ===============");//Get all the properties of this class field[] Declaredfields = Clazz.getdeclaredfields (); for (Field field:declaredfields) {//permission modifier int modifiers = field.getmodifiers ();    String priv = modifier.tostring (modifiers);//property type Class<?> type = Field.gettype (); System.out.println (Priv + "" + type.getname () + "" + field.getname () + ";");} System.out.println ("=============== implements the interface or property of the parent class field ==========");        System.out.println ("=============== the public Type property of the current class and its parent class or interface ==========");        Gets the implemented interface or property of the parent class field[] fields = Clazz.getfields (); for (Field field:fields) {//permission modifier int modifiers = field.getmodifiers ();    String priv = modifier.tostring (modifiers);//property type Class<?> type = Field.gettype (); System.out.println (Priv + "" + type.getname () + "" + field.getname () + ";");}} /** * Get all the methods of a class * @throws classnotfoundexception */@Testpublic void test05 () throws ClassNotFoundException {class<?& Gt Clazz = class.forname (className); System.out.println ("=============== all methods that the current class can invoke ==============="); Method[] methods = Clazz.getmethods (); for (Method method:methods) {class<?> returntype = Method.getreturntype (); class<?>[] parametertypes = Method.getparametertypes (); class<?>[] Exceptiontypes = Method.getexceptiontypes (); int modifiers = Method.getmodifiers (); String priv = modifier.tostring (modifiers); StringBuffer content = new StringBuffer () content.append (priv + "+ returntype.getname () +" "+ method.getname () +" (" );//method parameter type collection if (null! = parametertypes && parametertypes.length > 0) {for (class<?> Parametertype:param Etertypes) {content.append (Parametertype.getname () + "+", ");} Content.delete (Content.length ()-1, Content.length ());} Content.append (")");//method throws an exception if (null! = exceptiontypes && exceptiontypes.length > 0) {content.append ("thro WS "); for (class<?> exceptiontype:exceptiontypes) {content.append (Exceptiontype.getname () + " " + ",");}    Content.delete (Content.length ()-1, Content.length ());} SYSTEM.OUT.PRINTLN (content);}} /** * Method of invoking a class by reflection mechanism * @throws SecurityException * @throws nosuchmethodexception * @throws illegalaccessexception * @th Rows instantiationexception * @throws invocationtargetexception * @throws illegalargumentexception */@Testpublic void T Est06 () throws ClassNotFoundException, Nosuchmethodexception, SecurityException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {class<?> clazz = Class.forName ( ClassName); System.out.println ("=============== Java reflection mechanism-calls a method of a class ToString ==============="); Object obj = Clazz.newinstance ();// Call the Setusername method of Userimpl. Premise: Instance method = Clazz.getmethod ("Setusername", string.class); Object result = Method.invoke (obj, "Zhang San"); System.out.println ("Java reflection mechanism-calls a method of a class Setusername:" + result);//calls the ToString method of Userimpl. Premise: Instance Method method2 = Clazz.getmethod ("toString"); Object result2 = Method2.invoke (OBJ); System.out.println ("Java reflection mechanism-call a method of a class ToString:" + result2);}  /** * Manipulate properties of a class by reflection mechanism * @throws ClassNotFoundException * @throws illegalaccessexception * @throws instantiationexception * @throws SecurityException * @throws nosuchfieldexception */@Testpublic void test07 () throws ClassNotFoundException, I Nstantiationexception, Illegalaccessexception, nosuchfieldexception, SecurityException {Class<?> clazz = Class.forName (ClassName); System.out.println ("=============== Java reflection mechanism-manipulating the properties of a class ==============="); Object obj = Clazz.newinstance (); Field Declaredfield = Clazz.getdeclaredfield ("UserName");//You can assign a value directly to the property of private//java.lang.illegalaccessexception: Class Bean. Reflecttest can not access a member of Class Bean. Userimpl with modifiers "private" declaredfield.setaccessible (True);d eclaredfield.set (obj, "Java Reflection mechanism"); System.out.println (Declaredfield.get (obj)); System.out.println (obj);} /** * Gets the constructor */@Testpublic void test08 () throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {class<?> clazz = Class.forName ( ClassName); System.out.println ("=============== Java reflection mechanism-get constructor ==============="); Constructor<?>[] Constructors = clazz.getconstructors (); if (null! = Constructors && Constructors.length  >0) {for (constructor<?> constructor:constructors) {System.out.println ("Construction Method:" + Constructor); }object user1 = Constructors[0].newinstance (); Object user2 = constructors[1].newinstance ("User name ah"); System.out.println (user1); System.out.println (User2);}} /** * Call Set and get method * @throws classnotfoundexception * @throws illegalaccessexception * @throws instantiationexception * /@Testpublic void test09 () throws ClassNotFoundException, Instantiationexception, illegalaccessexception {class<? > clazz = Class.forName (className); System.out.println ("=============== Java reflection mechanism-call set and get Method ==============="); Object obj = Clazz.newinstance (); Setter ( obj, "UserName", string.cl"The name"); System.out.println ("Object after set:" +obj); object result = Getter (obj, "userName"); System.out.println ("Get Get Content:" + result);} /** * Obtain and modify the information of the array by reflection */@Testpublic void test10 () {int[] temps = {1, 2, 3, 4, 5}; System.out.println ("=============== Java reflection mechanism-get and modify the information of an array ===============");//Get array internal type class<?> ComponentType = Temps.getclass (). Getcomponenttype (); SYSTEM.OUT.PRINTLN ("Array type:" + componenttype.getname ()); SYSTEM.OUT.PRINTLN ("Array length:" + array.getlength (temps)); System.out.println ("The first element of the array:" + array.get (temps, 0)); Array.set (temps, 0, 100); System.out.println ("The first element of the array after modification is:" + array.get (temps, 0));} /** * Modify the size of the array by reflection mechanism */@Testpublic void test11 () {System.out.println ("=============== Java reflection mechanism-Modify the size of the array ===============" ); int[] temps = {1, 2, 3, 4, 5, 6, 7, 8, 9};int[] Newtemps = (int[]) modifyarraylength (temps,);p Rintarray (newtemps); S Tring[] ATR = {"A", "B", "C"}; String[] str1 = (string[]) modifyarraylength (ATR, 8);p Rintarray (STR1);} /** * Store A stri in the ArrayList of the generic integerAn object of type ng. * @throws SecurityException * @throws nosuchmethodexception * @throws invocationtargetexception * @throws illegalargume Ntexception * @throws illegalaccessexception */@Testpublic void test12 () throws Nosuchmethodexception, Securityexceptio N, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {System.out.println ("============== = Java Reflection mechanism-holds an object of type string in the ArrayList of the generic integer. ==============="); list<integer> list = new arraylist<integer> (); @SuppressWarnings ("Rawtypes") class<? Extends list> class1 = List.getclass (); method = Class1.getmethod ("Add", Object.class); Method.invoke (list, "This is: object of type string"); SYSTEM.OUT.PRINTLN (list);} /** * Apply reflection mechanism to Factory mode * Imitate Spring * @throws Exception */@Testpublic void test13 () throws Exception {System.out.println ("= = ============= Java Reflection Mechanism-Applies the reflection mechanism to the Factory mode =============== "); Factoryimpl factory = new Factoryimpl (); Userimpl user = Factory.getbean (classname,userimpl.class); SYSTEM.OUT.PRINTLN (user);} /** * The dynamic proxy of the reflection mechanism */@Testpublic void test14 () {System.out.println ("=============== Java reflection mechanism-Dynamic proxy =============== of the Reflection mechanism"); Myinvocationhandler demo = new Myinvocationhandler (); Userimpl Userimpl = new Userimpl ();        User user = (user) demo.bind (USERIMPL);        User.setname ("Rollen"); SYSTEM.OUT.PRINTLN (user);} /** * Internal class * Implementation call Processing interface * @author Chenchuan * */class Myinvocationhandler implements Invocationhandler {private Object OB    j = null;        public object bind (object obj) {this.obj = obj;        ClassLoader ClassLoader = Obj.getclass (). getClassLoader (); Class<?>[] interfaces = Obj.getclass (). getinterfaces ();//The parent class of the target class and the interface, you can find the execution of the target method, first execute the parent class or interface corresponding method return Proxy.ne    Wproxyinstance (classloader,interfaces, this); The public object invoke (object proxy, method, object[] args) throws Throwable {System.out.println ("target method (" + M        Ethod + ") before beginning ...");        Object temp = Method.invoke (this.obj, args);      System.out.println ("Target method (" + method+ ") after end ...");  return temp; }}/** * Print * @param obj */public static void PrintArray (Object obj) {class<?> c = Obj.getclass (); if (!c.isarray ()) {return;} SYSTEM.OUT.PRINTLN ("Array length is:" + array.getlength (obj)); for (int i = 0; I < array.getlength (obj); i++) {System.out.print (Array.get (obj, i) + "");}    System.out.println (); }/** * Modify the array size * @param obj * @param newlength * @return */public object Modifyarraylength (object obj, int Newleng        Th) {class<?> ComponentType = Obj.getclass (). Getcomponenttype ();        Object NewArray = array.newinstance (ComponentType, newlength);        int co = array.getlength (obj);        System.arraycopy (obj, 0, NewArray, 0, CO);    return newarray; }/** * * Execute Get method * @param obj Action Object * @param properties of FieldName action */public Object Getter (Object obj, String fieldName) {string Buffer methodName = new StringBuffer (); Methodname.append ("get");//sb.append (fieldname.substring (0, 1). toUpperCase () );//sb.append (fieldname.substring (1)); Methodname.append (Getmethodname (FieldName)); Object invoke = null;try {method = Obj.getclass (). GetMethod (Methodname.tostring ()); Invoke = Method.invoke (obj, new object[0]);} catch (Nosuchmethodexception e) {e.printstacktrace ();} catch (SecurityException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( InvocationTargetException e) {e.printstacktrace ();} return invoke; /** * @param obj * operation of the object * @param fieldName * Action Properties * @param the property of the type * parameter * @param value * Set the value of * */public void Setter (Object obj, String fieldName, class<?> type, object ... value) {Stringbuffe R methodName = new StringBuffer (), Methodname.append ("set")//sb.append (fieldname.substring (0, 1). toUpperCase ());// Sb.append (fieldname.substring (1)); Methodname.append (Getmethodname (FieldName)); try {method = Obj.getclass (). GetMethod (Methodname.tostring (), type); Method.invoke (obj, value);} catch (Nosuchmethodexception e) {e.printstacktrace (),} catch (SecurityException e) {e.printstacktrace ();} catch ( Illegalaccessexception e) {e.printstacktrace (),} catch (IllegalArgumentException e) {e.printstacktrace ();} catch ( InvocationTargetException e) {e.printstacktrace ();}}          /** * capitalizes The first letter of a string, is the highest efficiency, * @param fildename * @return * */private string Getmethodname (string fildename) {          byte[] items = fildename.getbytes ();          Items[0] = (byte) ((char) items[0]-' a ' + ' a ');      return new String (items); }  }

  

Java_ Reflection _ and its simple application (2016-11-16)

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.