Java Reflection Detailed

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 package Com.ys.reflex; 2 public class The person {3     //private Property 4 privately     String name = "Tom"; 5     //Common attribute 6 "int" age =     ; 7     //Construction Method 8 Public Person     () {     9     }10     //Private method one by one private     void Say () {         System.out.println ("Private say () ()     }14     //Public Method: () () (     ) {         System.out.println ("Common work () ...");     }18}

①, three ways to get Class

1//1, through the object call GetClass () method to obtain, usually applied in: for example, you pass an object 2//  type of objects, and I do not know what you specifically class, in this way 3 person p1 = new Person (); 4 C Lass C1 = P1.getclass (); 5          6//2, directly through the class name. Class, the method is most safe and reliable, the program performance is higher 7//  This indicates that any class has an implied static member variable Class 8 class C2 = Person.class; 9
   10//3, through the class object's forname () static method to obtain, with the most, one//   but may throw the classnotfoundexception exception of the class 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 class complete Name 2 String className = C2.getname (); 3 System.out.println (className);//Output Com.ys.reflex.Person 4 5//Gets the properties of the public type of the class. 6 field[] fields = C2.getfields (); 7 for (Field field:fields) {8 System.out.println (Field.getname ());//age 9}10 11//Gets all the properties of the class. Includes the private and inheriting classes of the field [] AllFields = C2.getdeclaredfields (); (Field field:allfields) {System.out.println (FIELD.G Etname ());//name age15}16 17//Gets the method of the public type of the class. Here are some methods of the Object class [] methods = C2.getmethods (); (method Method:methods) {System.out.println (method). GetName ());//work waid equls toString hashcode et 21}22 23//Get all methods of the class. method [] Allmethods = C2.getdeclaredmethods (); (method Method:allmethods) {System.out.println (method.getn Ame ());//work say27}28 29//Get the property specified in Field f1 = C2.getfield ("Age"); System.out.println (F1); 32//Get the specified private property Eld F2 = C2.getdeclaredfield ("name"); 34//Switch to enable and disable access security checks, and true to indicate that objects that are reflected should cancel access checks of the Java language when they are used;F2.setaccessible (True); System.out.println (F2); 37 38//Create an object of this class. All Objects P2 = c2.newinstance (); 40 Assigning the F2 property of the P2 object to the Bob,f2 property is the private property name41 F2.set (P2, "Bob"), and 42////using the reflection mechanism to break the encapsulation, which makes the properties of the Java object unsafe. System.out.println (F2.get (p2)); BOB44 45//Get construction method Constructor [] constructors = c2.getconstructors (); Tors) {System.out.println (constructor.tostring ());//public Com.ys.reflex.Person () 49}

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!

Java Reflection Detailed

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.