The information that the Java reflection mechanism can obtain, and the application

Source: Internet
Author: User
Tags modifier

"1" reflection mechanism is in the running state, for any one class, can know all the properties and methods of this class;

"2" is capable of invoking any of its properties and methods for any object;

Such dynamic fetching of information about the class and the method of dynamically invoking the object are called the reflection mechanism of the Java language.

Second, what information can the Java reflection mechanism obtain and manipulate?

"1" gets the package name + class name of the class

 1 package com.zyy.test.reflect;         2 3 public class Testreflect {4 5 public static void main (string[] args) throws ClassNotFoundException {6 class<?> Class1 = Testreflect.class; 7 class<?> class2 = new Testreflect (). GetClass (); 8 class<?> CLASS3 = Class.forName ("Com.zyy.test.reflect.TestReflect"); 9 System.out.println ("package name + Class Name:" + class1.getname ()); System.out.println ("Class name" + Class1.getsimple Name ()); System.out.println ("Package name + Class Name:" + class2.getname ()); System.out.println ("Class name" + Class2.getsimplena Me ()); System.out.println ("Package name + Class Name:" + class3.getname ()); System.out.println ("Class name" + Class3.getsimplename ()); 16 17/*18 printing results are as follows: 19 Package name + Class Name: com.zyy.test.reflect.TestReflect20 class name Testr EFLECT21 Package name + Class Name: com.zyy.test.reflect.TestReflect22 class name TestReflect23 package name + class Name: COM.ZYY.TEST.R Eflect. TestReflect24 class name TestreflEct25 */26}27 28} 

"2" gets the interface information for the parent class of a class and implementation

1 package com.zyy.test.reflect; 2  3 import java.io.Serializable; 4  5 public class Testreflect implements serializable{6  7     Private Static final Long serialversionuid = -8047590384784013451l; 8  9 public     static void Main (string[] args) throws ClassNotFoundException {Ten         class<?> clazz = Class.forName ("Com.zyy.test.reflect.TestReflect");         get the parent class information         System.out.println ("Parent class:" + Clazz.getsuperclass (). GetName ());         //Get all interface information for the implementation of         class<?>[] interfaces = Clazz.getinterfaces ();         (int i = 0; i < interfaces.length; i++) {             System.out.println ("interface:" + interfaces[i].getname ()); 17
   }18         /         * Print results as follows:             parent class: Java.lang.Object21             interface: Java.io.Serializable22          */23     }24 25 }

"3" Gets the construction information for a class and uses constructs to assign values

 1 package com.zyy.test.reflect; 2 3 Import Java.lang.reflect.Constructor; 4 Import java.lang.reflect.InvocationTargetException; 5 Import Java.math.BigDecimal; 7 8 public class Testreflect {9. public static void Main (string[] args) throws ClassNotFoundException, Instant         Iationexception, Illegalaccessexception, IllegalArgumentException, invocationtargetexception {12 13 Class<?> clazz = Class.forName ("com.zyy.test.reflect.BookFacaed"); constructor<?>[] Constructor s = clazz.getconstructors (), 0 for (int i =; i < constructors.length; i++) {System. Out.println (the "construct" + i + constructors[i].getname () + "parameter is:"); 18//Gets the parameter information for the construct [class<?>[] Type s = Constructors[i].getparametertypes (); (int j = 0; J < Types.length; J + +) {Syste        M.out.println (Types[j].getname () + ""); 22}23}24 25/* Print Result: 26      The parameters for constructing 0com.zyy.test.reflect.bookfacaed are: java.lang.String java.math.BigDecimal 29 The parameters for constructing 1com.zyy.test.reflect.bookfacaed are: java.lang.String 31 construction 2COM.ZYY.TEST.REFLECT.BOOKFA The parameters of the caed are: 32 */33 34//Instantiate a constructor with 2 parameters bookfacaed bookfacaed = (bookfacaed) constructors[0    ].newinstance ("Data Structure", new BigDecimal); System.out.println (bookfacaed); The ToString method of the calling entity Prints 37 38//directly instantiates the object via a reflection mechanism of bookfacaed BookFacaed2 = (bookfacaed) clazz.newinstance ( ); Bookfacaed2.setname ("Data Structure"); Bookfacaed2.setprice (new BigDecimal); System.out.prin TLN (BOOKFACAED2),}44}46 class Bookfacaed {$ private String name;49 Private BigDecimal PR     Ice;51 bookfacaed () {}53-public bookfacaed (String name) {this.name = name;56 }57 bookfacaed (String name, BigDecimalPrice) {this.name = name;60 This.price = price;61}62 The public String getName () {64 return name;65}66 public void SetName (String name) {this.name = name;69}70 the public Big Decimal GetPrice () {price;73 return,}74, public void Setprice (BigDecimal price) {this.pric     E = price;77}78 @Override80 public String toString () {Bayi return name + "The price is:" + price;82 }83}

"4" gets all the property information for a class

 1 package com.zyy.test.reflect; 2 3 import Java.lang.reflect.Field; 4 import java.lang.reflect.modifier;public Clas S Testreflect {5 6 public static void main (string[] args) throws ClassNotFoundException {7 CLASS<?&G T Clazz = Class.forName ("Com.zyy.test.reflect.BookFacaed"); 8 field[] fields = Clazz.getdeclaredfields (); 9 for (int i = 0; i < fields.length; i++) {10//Get Modifier for class Property one by one String pri = modifier.tostr             ING (fields[i].getmodifiers ()); 12//Get Class Property type class<?> type = Fields[i].gettype (); 14 System.out.println (pri + "" + type.getsimplename () + "" + fields[i].getname ()); 16/* Print Results         : + Private String name18 private BigDecimal price19 */20}21 22/* If you want to get the interface of a class or the properties of a parent class use the following method to get */23 field[] fields2 = Clazz.getfields ();}25 +} 

"5" gets all the methods and their property information for a class

 1 package com.zyy.test.reflect; 2 3 Import Java.lang.reflect.Method; 4 Import Java.lang.reflect.Modifier; 5 Import Java.math.BigDecimal;         6 7 8 public class Testreflect {9 public static void Main (string[] args) throws ClassNotFoundException {11 Class<?> clazz = Class.forName ("com.zyy.test.reflect.BookFacaed"); method[] methods = CL Azz.getmethods (); + for (int i = 0; i < methods.length; i++) {System.out.println ("method" + (i + 1)) ; 16//Gets the modifier of the method in the String pri = modifier.tostring (Methods[i].getmodifiers ()); 18//Gets the return of the method class<?> type = Methods[i].getreturntype (); 20//acquisition method holding parameters of class<?> [] params = Methods[i].getparametertypes (); (int j = 0; J < Params.length; J + +) {% S Ystem.out.println (Params[j].getname ()); 24}25//Gets the exception of the method to be thrown class<?>[] Exctypes = MethoDs[i].getexceptiontypes (); (int j = 0; J < Exctypes.length; J + +) {System.out.print ln (exctypes[j].getname ()); 29}30}31}32 33}

the "6" reflection mechanism calls a method of a class

 1 package com.zyy.test.reflect; 2 3 Import java.lang.reflect.InvocationTargetException; 4 Import Java.lang.reflect.Method; 5 Import Java.math.BigDecimal; 6 7 public class Testreflect {8 9 public static void Main (string[] args) throws Nosuchmethodexception, Security  Exception, ClassNotFoundException, Illegalaccessexception, IllegalArgumentException, InvocationTargetException,         instantiationexception {class<?> clazz = Class.forName ("Com.zyy.test.reflect.BookFacaed"); 13 Call Bookfacaed's Addbook () method by means method = Clazz.getmethod ("Addbook", String.class); Voke (Clazz.newinstance (), "Data Structure"),}17}19 class Bookfacaed {$ private String name;22-PR Ivate BigDecimal price;24 Public bookfacaed () {}26-public bookfacaed (String name) {-This . Name = name;29}30 bookfacaed (String name, BigDecimal price) {this.name = name;33         This.price = price;34}35-public void Addbook (String name) {Notoginseng System.out.println ("Add Book:" + }39-Public String getName () {name;42}43, public void SetName (string     Name) {this.name = name;46}47 BigDecimal getprice () {price;50}51 52 public void Setprice (BigDecimal price) {this.price = price;54}55-@Override57 public stri The price for NG toString () {price;59 return name + "is:" +}60}

"7" manipulating the properties of a class through a reflection mechanism

1 package com.zyy.test.reflect; 2  3 import Java.lang.reflect.Field; 4 import java.math.BigDecimal; 5  6 public class Testreflect {7      8     Pub Lic static void Main (string[] args) throws ClassNotFoundException, Nosuchfieldexception,  9         SecurityException, IllegalArgumentException, Illegalaccessexception, instantiationexception {ten         class<?> clazz = Class.forName ("Com.zyy.test.reflect.BookFacaed");         Object obj = clazz.newinstance ();         Call the Name property of Bookfacaed and assign a value of         field field = Clazz.getdeclaredfield ("name");         field.setaccessible (true); The Action property modifier is private and must be used with this declaration         field.set (obj, "data structure");         System.out.println (field.get (obj)); 19     }20     21}

Third, what can the Java reflection mechanism do to help us?

"1" breaks the constraints of generics

1 package com.zyy.test.reflect; 2  3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import Java.math.BigDecimal; 6 Import java.util.ArrayList; 7 Import Java.util.List; 8  9 public class Testreflect {Ten     public     static void Main (string[] args) throws Nosuchmethodexception, Secu Rityexception,         illegalaccessexception, IllegalArgumentException, invocationtargetexception {         list<integer> list = new arraylist<integer> ();         after setting the above generics, the list collection is not able to insert string or other types of data         By generics we can break this constraint, as shown in the code of         method = List.getclass (). GetMethod ("Add", Object.class);         Method.invoke ( List, "See Insert a String data");         System.out.println (list.get (0));     }22     23}

"2" reflection mechanism to implement dynamic proxy

One of spring's core design ideas is AOP (aspect-oriented programming), then AOP is implemented by dynamic proxies, while dynamic agents use the reflection mechanism;

The advantage of using a reflection mechanism is that an agent can handle all the delegates without having to create an agent without a delegate class;

 1 package com.zyy.test.reflect; 2 3 Import Java.lang.reflect.InvocationHandler; 4 Import Java.lang.reflect.Method; 5 Import Java.lang.reflect.Proxy;         6 7 8 public class Testreflect {9 public static void Main (string[] args) {11//Create proxy class and bind delegate class 12 Fruitproxy proxy = new Fruitproxy (), Fruit Fruit = (Fruit) proxy.bind (New Apple ()), Fruit.eatfruit ();      }16}18 interface Fruit {25 public void eatfruit (); 21}22 23//Delegate class Apple implements Fruit public void Eatfruit () {System.out.println ("Eat Apple"), 27}28}29 30//proxy class Fruitproxy Impleme NTS invocationhandler{32 Private Object obj;33 34//bound object A public object bind (object obj) {The . obj = obj;37 return proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this)            ;}39 @Override41 public Object Invoke (object proxy, Method method, object[] args) 42 Throws Throwable {System.out.println ("Add the execution content here,<aop:before/> tag familiar, function the same"); Method result = (Met         Hod) Method.invoke (obj, args), System.out.println ("Add the execution content here,<aop:after/> tag familiar, function the same"); 46 47 return result;48}49 50}

"3" reflection mechanism applied to Factory mode

For a normal factory, when a new subclass is added, the factory needs to be adjusted, and after adding a reflection mechanism, the factory does not need to care about how many subcategories you have;

1 package com.zyy.test.reflect; 2  3 public class Testreflect {4      5 public     static void Main (string[] args) throws Instantiationexception,  6         illegalaccessexception, classnotfoundexception {7          8         Fruit Fruit = (Fruit) factory.getinstance (" Com.zyy.test.reflect.Orange "); 9         fruit.eatfruit ();     }11     }13 interface Fruit {public     void Eatfruit ();}17 class Apple Impl Ements Fruit {public     void Eatfruit () {         System.out.println ("Eat Apple"),     }22}23 class Orange Imp Lements Fruit {public     void Eatfruit () {         System.out.println ("Eat Orange"),     }28}29 class Factory {     to public static Object getinstance (String className) throws Instantiationexception,         Illegalaccessexception, classnotfoundexception {         Object obj = Class.forName (className). newinstance () ;         return obj;36     }37     38}

The information that the Java reflection mechanism can obtain, and the application

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.