Java reflection in layman's (i)

Source: Internet
Author: User

There are two ways to create a class instance in the JVM, one at compile time and the other at runtime. Both of these approaches are important in the development process. In Java, the ubiquitous Java object, the process of instantiation becomes particularly noticeable. We often use the new object () method to create an instance, whereas reflection at this time is abrupt, because someone would ask, why not just new object when the Java object instance? In fact, the situation is forced, sometimes, we do not know what to do when compiling the object, the object's bytecode does not know where there is? is on a computer in the hard drive, in memory, or on the other side of the world, so we're going to write it this time in a different, tactful way.

Analysis

There are different portion in a class, while field (attribute), Constructor (constructor), method (methods) are three important parts. We're just going to invoke this three-part operation on a class.       So by reflection, we get these attribute to operate. We also need to understand that since everything in Java is an object, the parts of a class can be taken out individually as different objects. This is conducive to the understanding of our object thinking andSimplificationwrite the code.  
    • Understanding of byte codes
    • Construtor
    • Field
    • Method
    • The relationship between array arrays and object
    • Create a Newinstance object
  Example Explanation understanding of byte codesAll objects in the JVM, in the computer's memory, in the computer's hard disk, in fact, are in binary form. So are we going to understand the bytecode in Java and think about it, or is the binary content form present in the computer? Right, then this time to understand this part is actually much simpler. Whether it's String,integer or char, it's a messy 0011. We ignore this seemingly complicated part to see the real problem, in the final analysis, is a stack of data and symbols.
  1. 1String str1 = "abc";2Class CLS1 =Str1.getclass ();3Class cls2 =string.class;4Class cls3 =class.forname ("java.lang.String");5 System.out.println (Str1.getclass ());6System.out.println (CLS1 = =cls2);7System.out.println (CLS3 = =cls2);8 /**9 Output ResultsTen class Java.lang.String One true A true - */

One instance of string is str1, so str1 's class isjava.lang.Stringso we found String.class and passedclass.forname ("java.lang.String") to get a class is actually a class of String in the JVM. In addition, there are some methods of class (Everything is an object, the object itself is an object, has its own characteristics)
    1. 1 System.out.println (int[].  Class. Isprimitive ()); 2 System.out.println (int[].  Class. IsArray ());

ConstrutorA class must first have an argument-free construction method, followed by a possible method of constructing a parameter. At the same time we know the overload of the method, the main difference is the number of parameters and the type of difference. Then construtors may have multiple constructs, so Java provides a concrete way to construct or get all the constructs.
    1. // get all the construction methods // Constructor Constructor[] Constuctor =class.forname ("java.lang.String"). GetConstructors (); // the construction method of obtaining the parameter as StringBuffer Constructor Constructor =class.forname ("java.lang.String"). GetConstructor (StringBuffer.  Class);

Field       The properties owned by the class, private or public. We're going to get all the field, possibly in the case of the private attribute, you need to passGetdeclaredfield andsetaccessible to get this property.
 Public classreflectpoint{//properties for private and publicPrivate intx; Public inty; PublicReflectpoint (intXinty) {Super(); This. y =y; This. x =x;} Publicstring toString () {System.out.println (str1+ str2 +STR3);returnSTR1 + str2 +str3;}}//FieldReflectpoint pt1 =newreflectpoint (3,5); Field Fieldy= Pt1.getclass (). GetField ("Y"); System.out.println (Fieldy.get (PT1)); Field FIELDX= Pt1.getclass (). Getdeclaredfield ("x"); Fieldx.setaccessible (true); System.out.println (Fieldx.get (PT1));/**Result:*/

    1.        
In this way, you can know that the properties of private and public are required to be obtained by different methods. at the same time we can get the value of field by reflection and then change the value. Call the following method, the value in the property of the passed in object will be replaced by the B
Private Static void changestringvalue (Object obj) throws exception{//  TODO auto-generated method stubfield[] Fields = Obj.getclass (). GetFields ();  for (Field field:fields) {if(Field.gettype () ==string.  Class== Oldvalue.replace ("A", "B"); Field.set (obj, newvalue); }}

MethodActually get a class in the method, and the construction method is actually the same, the first parameter is the method name, the second parameter is the type of the method passed in parameters, if there are more parameters, you can continue to write in.
    1. Method methods String str1 = "a"; Method Methodcharat =string.class.getmethod ("CharAt", Int.class); System.out.println (Methodcharat.invoke (str1,1));//str1 is an instance object of string

        

At the same time the start of the method is with the first parameter of invoke is an entity containing the class of this method. The second parameter is the actual data of the various parameters to be passed in this method. Of course, static methods sometimes do not require instance objects, because when Java is running, the instances of these static methods exist in the JVM, so invoke can be null,invoke (null, new object[]{new string[]{"111","222","333" }});  the relationship between array arrays and objectwhat type of an object can it be? We know that all classes are based on object as the parent class, but what about arrays? String is not the 8 big data type of Java, the parent of string is object, but the 8 big data types in Java (Boolean,byte,Char,Short,int,Float,long,double) In fact, the corresponding Java classes are (Boolean, Byte, Character, short, Integer, Float, Long, double) the parent class of these encapsulation classes is object, they are not, So, when we save these data types in an array, the array is an object, but the array of strings can be represented by object[]. Speaking so much, we can do things with the reflection of arrays.
/*** Reflection of the array *@paramO1*/Private Static voidPrintObject (Object O1) {//TODO auto-generated Method StubClass Clazz =O1.getclass ();if(Clazz.isarray ()) {intLength =array.getlength (O1); for(inti = 0; i < length; i++) {System.out.println (Array.get (O1, i));}}Else{System.out.println (O1);}}int[] A1 =newint[]{1,2,3};int[] A2 =newint[4];int[][] A3 =newint[3][4]; String[] A4 =newstring[]{"A", "B", "C"};p rintobject (A1);p rintobject (A4);

Note here that the array of strings can be represented by object, and also by object[].Create a Newinstance objectThis is relatively simple, by getting a class object, and then newinstance it.
    1. String obj = (string) class.forname ("java.lang.String"). newinstance ();

End: We know that the real change is growing in practice. (irrelevant haha)



From for notes (Wiz)



Java reflection in layman's (i)

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.