Dark Horse programmer--java High-tech--reflection of replication

Source: Internet
Author: User

Because the first video learning effect is not ideal, hope to re-see the reflection of the video, and various aspects of the search for information, re-write a summary, in order to improve the early Java capabilities.

java--Reflex

First, class

  ClassInstances of the class represent classes and interfaces in a running Java application. So, class can provide methods to get the various properties in the dynamic Java class;

(The idea that a class is created by definition is to get the information of a particular Java class and then pass it to the object of class, then what exactly?) )

The Java class information here refers to the Java class's computer's bytecode: passed to class CLS1:

So there are three different directions to get

1. Obtained from the class name: Class name.

2. Obtained from the specific object: Person p1=new person (); Byte code: P1.getclass ();

The 3.Class class has its own static method, which can specify the bytecode of a class: Class.forName ("java. Lang.string ");

When doing reflection, generally use the third kind: because of writing the original program, my class may not have been created;

Note: Eight data types and void, predefined class names, direct class name. class to create class.

1String strl="ABC";2Class cls1=string.class;3Class cls2=Strl.getclass ();4Class Cls3=class.forname ("java.lang.String");//Finally, the clock is classnotfoundexception .5 //determine if the three are the same, because how much of the same class is the same byte code?6System. out. println (cls1==cls2);7System. out. println (cls1==CLS3);8         9 //The class.isprimitive () method is the Class that determines whether the underlying data type correspondsTenSystem. out. println (Cls1.isprimitive ());//it must be false . OneSystem. out. println (int.class. isprimitive ());//must be true . ASystem. out. println (int.class==integer.class);//Integer is a class, brother. -System. out. println (int.class==integer.type);//However, these guaranteed classes provide a method. Type returns the specified types -System. out. println (int[].class. isprimitive ());//array of course not. theSystem. out. println (int[].class. IsArray ());//but Class.isarray can tell if an array

Second, the definition and meaning of reflection:

Reflection is the mapping of the various components in the Java class into the corresponding Java classes (that is, the Class), which provides a series of methods to get the variables, methods, and construction methods

modifiers, packages and other information, which are represented by corresponding instance objects, they are field, Method, Contructor, package, etc.

Since each member of a class can be represented by reflection, how to get the instance objects of these class classes, how they are used, where they are used, is the point of reflection:

Iii. Constructor (class to obtain a construction method)

(1) Access: The Class class provides a method: GetConstructors () (Note: There is an S, which means to get the constructor in this class)

For example: constructor[] Constructor=class.forname ("java.lang.String"). GetConstructors;

GetConstructor (parameters) to obtain a parameter corresponding to the characteristics of the construction method:

For example:

(2) You can call the class class in the GetConstructor (String.class,int.class) method to get the specified constructor,

The use of newinstance ("Zahns", 23) to obtain specific objects;

1 //about the constructor class, about new String (new Stirngbuilffer ("abc"))2Constructor constructor1=string.class. GetConstructor (StringBuffer.class);//get the construction method corresponding to this particular parameter3String str=4(String) Constructor1.newinstance (NewStringBuffer ("ABC"));5         //and New String (New Stirngbuilffer ("abc")) one meaning, pay attention to the strong turn6System. out. println (Str.charat (2));//the answer is C .

(My understanding: GetConstructor and Newinstance This is a single step can be said to declare the specific type, and then the specific incoming what type)

(3) Class.newinstance () Method:

String obj= (String) class.forname ("Java: Lang. String "). Newsinstance ();

The method is constructed by default, and then the object is created by constructing the method.

The Newinstance () method in class is to create an object using the parameterless constructor, which cannot be created if a class does not have a constructor for the parameter.

Iv. field Class (Fields, variables)

The *class.getfidle ("Variable name") method can obtain the field specified in the class, and then obtain the actual value using the Get (class name object) in field.

* And if the field is private when using violent reflexes, the employing Getdeclaredfield ("variable name") gets, via get (obj, "")

Reflecpoint is a custom class, x private, Y public

1Reflecpoint pt1=NewReflecpoint (3,5);2Field Fiely=pt1.getclass (). GetField ("y");3 //This still doesn't get the value of Y.4System. out. println (fiely.Get(PT1));//is 55 //then the private need to use violent reflexes6Field Fielx=pt1.getclass (). Getdeclaredfield ("x");7Fielx.setaccessible (true);//this is a must.8System. out. println (Fielx.Get(PT1));//is 3
1  Public classReflecpoint {2     Private intx;3      Public inty;4     5String pp1="ASFSDFSDG";6String pp2="ASFSASDDG";7String pp3="ASFSDFADDG";8      PublicReflecpoint (intXinty) {9 //super (); defaultTen          This. x =x; One          This. y =y; A     } -      PublicString toString () { -         returnpp1+":"+pp2+":"+pp3; the     } -}
1Reflecpoint pt1=NewReflecpoint (3,5);2 Changestringvalue (PT1);3System. out. println (PT1);4     }5 //Change B of string in variable to a6     Private Static voidchangestringvalue (Object obj) throws Exception {7Field[] Fields=Obj.getclass (). GetFields ();8          for(Field field:fields) {9             if(Field.gettype () ==string.class){//The comparison is whether the bytecode is the sameTenString old= (String) field.Get(obj); OneString News=old.replace ('b','a'); AField.Set(obj, news); -             } -}

V. Method class

Dark Horse programmer--java High-tech--reflection of replication

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.