Understanding of Java Reflection

Source: Internet
Author: User

Reflection reflection, Programmer's happiness, Are you happy today? If you are not happy, it doesn't matter, next make you happy!

first, What is reflection?
Through the Baidu Encyclopedia we can know that the Java reflection is in the running state, for any class, can know all the properties and methods of the class, for any object, can invoke its arbitrary methods and properties, and can change its properties. This is also what Java is considered dynamic (or quasi-dynamic, why it is quasi-dynamic, because in general the dynamic language definition is when the program runs, allowing the change of program structure or variable type, which is called dynamic Language. From this point of view, Perl,python,ruby is a dynamic language, and c++,java,c# is not a dynamic language. ) A key character of the Language.

second, What can reflection do?
We know that the reflection mechanism allows the program to get the internal information of any known-named class at run time, including its modifiers (modifier), fields (properties), methods (methods), and so on, and can change the contents of a domain or invoke methods at run Time. Then we can be more flexible to write code, code can be run-time assembly, do not need to link between the components of the source code, reduce the coupling of the code, as well as the implementation of dynamic agents and so on, but the need to pay attention to the use of reflection is very expensive!

third, the concrete realization of reflection

The following is a basic class of person

1  packagecom.ys.reflex;2  public classperson {3     //Private Properties4     PrivateString name = "Tom";5     //Public Properties6      public intAge = 18;7     //Construction Method8      publicperson () {9     }Ten     //Private Methods one     Private voidsay () { aSystem.out.println ("private say () ..."); -     } -     //Public Methods the      public voidwork () { -System.out.println ("public Work () ..."); -     } -}

①, three ways to get Class

1 //1, by the object call GetClass () method to obtain, usually applied in: for example, you pass an object.2 //type of object, and I don't know what your specific class is, in this way3person P1 =Newperson ();4Class C1 =P1.getclass ();5         6 //2, directly through the class Name. class, the method is the most safe and reliable, higher program performance7 //This means that any class has an implied static member variable class8Class C2 = Person.class;9         Ten //3, through the Class object forname () static method to obtain, with the most, one //but may throw ClassNotFoundException exception aClass C3 = Class.forName ("com.ys.reflex.Person");

It is important to note that a class will have only one class instance in the JVM, that is, we compare the c1,c2,c3 obtained above with equals and find that all is true

②, using class classes to get member variables, member methods, interfaces, superclass, construction methods, etc.

The lookup API can see the Class in a number of ways:

GetName (): Gets the full name of the class.
GetFields (): Gets the properties of the public type of the class.
Getdeclaredfields (): gets all the properties of the class. Include the private declaration and inheriting classes
GetMethods (): method that gets the public type of the class.
Getdeclaredmethods (): gets all the methods of the class. Include the private declaration and inheriting classes
GetMethod (String name, class[] parametertypes): Gets the Class's specific method, the name parameter specifies the name of the method, and the Parametertypes parameter specifies the parameter type of the Method.
GetConstructors (): Gets the construction method of the public type of the class.
GetConstructor (class[] parametertypes): Gets the specific constructor method for the class, and the parametertypes parameter specifies the type of the parameter for the constructed Method.
Newinstance (): creates an object of this class from the constructor of the class without Parameters.

We use an example to synthesize the above method:

1 //get the full name of the class2String ClassName =c2.getname ();3System.out.println (className);//Output Com.ys.reflex.Person4         5 //gets the properties of the public type of the class. 6field[] fields =C2.getfields ();7  for(Field Field:fields) {8System.out.println (field.getname ());// age9 }Ten          one //gets all the properties of the class. including private and inherited Classes. aField [] allFields =C2.getdeclaredfields (); -  for(Field Field:allfields) { -System.out.println (field.getname ());//name age the } -          - //gets the method of the public type of the class. Here are some methods of the Object class -Method [] methods =c2.getmethods (); +  for(Method Method:methods) { -System.out.println (method.getname ());//work Waid equls toString hashcode etc. + } a          at //gets all the methods of the class.  -Method [] allmethods =c2.getdeclaredmethods (); -  for(Method Method:allmethods) { -System.out.println (method.getname ());//work say - } -          in //gets the specified property -Field f1 = C2.getfield ("age"); to System.out.println (f1); + //gets the specified private property -Field F2 = C2.getdeclaredfield ("name"); the //the switch to enable and disable access security checks, which is true, indicates that the reflected object should cancel the access check of the Java language when it is used; *F2.setaccessible (true); $ System.out.println (f2);Panax Notoginseng                  - //create an object of this class theObject P2 =c2.newinstance (); + //assigning the F2 property of the P2 object to the Bob,f2 property is the private property name aF2.set (p2, "Bob"); the //using the reflection mechanism can break the encapsulation and cause the properties of the Java object to be Unsafe.  +System.out.println (f2.get (p2));//Bob -          $ //Get Construction Method $Constructor [] constructors =c2.getconstructors (); -  for(Constructor Constructor:constructors) { -System.out.println (constructor.tostring ());//public Com.ys.reflex.Person () the}

Iv. Summary of Reflections

Flexible use of reflection can make our code more flexible, such as the JDBC native code registration driver, hibernate entity class, Spring's AOP and so on have the reflection Implementation. But there are two sides to everything, reflection will also make the performance of the system, complexity and so on, reasonable use is true!

Understanding of Java Reflection

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.