Java reflection is a matter of fact.

Source: Internet
Author: User

What is reflection

java reflection mechanism: The Java Reflection Mechanism is in the running state,

For any class, all the properties and methods of the class can be known;

For any object, it can call any of its methods and properties;

This dynamic acquisition of information and the ability to dynamically invoke the object's methods is called the reflection mechanism of the Java language.

Simply put: restore the full information of a class based on an object that has already been instantiated

modifying properties by Reflection

 PackageTest2016.demo;ImportJava.lang.reflect.Field; Public classDemo4 { Public Static voidMain (string[] args)throwsException {Student stu=NewStudent (); Field[] Fields=Stu.getclass (). Getdeclaredfields ();  for(Field f:fields) {f.setaccessible (true); //Set whether to allow access, not write run will error                          if(F.getname () = = "Name") {F.set (Stu,"Java"); } Else if(F.getname () = = "Age") {F.set (Stu,20);    }} System.out.println (Stu); //Output: java:20    }}classStudent {PrivateString name; Private intAge ;  PublicStudent () { This. Name = "Zhangsan";  This. Age = 10; }        //override the ToString method, otherwise output: [email protected]     PublicString toString () {return  This. Name + ":" + This. Age; }}

Calling methods by reflection

 PackageTest2016.demo;ImportJava.lang.reflect.Method; Public classDemo4 {@SuppressWarnings ("Unchecked")     Public Static voidMain (string[] args)throwsException {Student stu=NewStudent ("Zhangsan", 21); Class C=Stu.getclass (); //the GetMethod () method needs to pass in the method name and the parameter type of the method with the parametermethod = C.getmethod ("Score",int.class); //Invoke () indicates the meaning of the call and needs to pass in objects and parametersMethod.invoke (Stu, 100); Method m= C.getmethod ("Say", String.class); //the null representation is not called by the object, which is the static method, and the null transposition Stu is also possible.M.invoke (NULL, "Hello java!!!"); }}classStudent {PrivateString name; Private intAge ;  PublicStudent (String name,intAge ) {         This. Name =name;  This. Age =Age ; }         Public voidScore (intscore) {System.out.println ( This. Name + "Test" + score + "Score"); }         Public Static voidsay (String str) {System.out.println ("Just now I said:" +str); } @Override PublicString toString () {return  This. Name + "-" + This. Age; }}

Program output: Zhangsan a 100-point test.
I said just now: Hello java!!!

manipulating arrays by reflection

 PackageTest2016.demo;ImportJava.lang.reflect.Array; Public classDemo4 { Public Static voidMain (string[] args)throwsException {int[] arr = {1, 2, 3, 4, 5}; //Getcomponenttype () returns the class name of the data type of the data contained in your array. This is int .class<?> C =Arr.getclass (). Getcomponenttype (); System.out.println ("Array type:" + c.getname ());//array type: int                intLen =array.getlength (arr); System.out.println ("Array Length:" + len);//Array Length: 5System.out.print ("Traversing array:");  for(inti = 0; i < Len; i++) {System.out.print (Array.get (arr, i)+ " ");//traversing arrays: 1 2 3 4 5} System.out.println (); System.out.println ("Before modifying the third data:" + Array.get (arr, 2));//before you modify a third data: 3Array.set (arr, 2, 10); System.out.println ("Before modifying the third data:" + Array.get (arr, 2));//before modifying a third data:    }}

Note the point :

  GetFields () differs from Getdeclaredfields ():

GetFields () can only access fields declared as public in a class, private fields that cannot be accessed, and access to public methods inherited from other classes.

Getdeclaredfields () can access all fields in a class, regardless of public,private,protect, and cannot access methods inherited from other classes

  GetMethods () differs from Getdeclaredmethods ():

GetMethods () can only access methods declared as public in a class, private methods that it cannot access, and access to public methods inherited from other classes.

Getdeclaredfields () can access all fields in a class, regardless of public,private,protect, and cannot access methods inherited from other classes

GetConstructors () differs from getdeclaredconstructors ():

GetConstructors () can only access constructors declared as public in a class.

getdeclaredconstructors () can access all constructors in a class, regardless of Public,private,protect

    

Java reflection is a matter of fact.

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.