Dark Horse programmer--java Basics-Reflex

Source: Internet
Author: User
Tags access properties

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

Reflection is in the running state, for any class (class file), you can know all the properties and methods of this class, for any one object, can only call its arbitrary methods and properties, the dynamic access to the information at the level of the dynamic method of invoking the object's function is called a Java reflection mechanism. Reflection is actually loading a specified class dynamically and getting all the content in that class. The bytecode files are encapsulated into objects and the contents of the bytecode files are encapsulated into objects, making it easier to manipulate those members. is to reflect the various components in the Java class into the corresponding Java class. Simply put: Reflection technology can dissect a class. If you want to load reflection on a bytecode file of the specified name, it greatly enhances the extensibility of the program. Basic steps for Reflection: 1. Get the class object, which is the bytecode file object that gets to the specified name. 2, instantiate the object, get the class's properties, methods, or constructors. 3. Access properties, call methods, call constructors to create objects. Get the same byte-code file for the class, in these three ways. 1.Class cls1= class name is relatively simple, you need to clarify the class name 2.cls1.getclass (), you must clear the specific class, and create the object 3.class.forname ("Full class name (with package name)"); 9 pre-defined class instance objects. Integer.class The byte code of the wrapper class Integer.type the byte code of the basic type in Integer Int.class==integer.type array class.isprimitive (); Class.isarray ();     As long as the types that appear in the source program have their own class instance objects, such as int[] void, and so on, create the object of the class String name= "Com.dsa. Class name";     Looking for the name class file and loading into memory, not producing Class object class Clazz=class.forname (name);      The object that produces the class is obj=clazz.newinstance ();     Gets a specified constructor method Constructor constructor= Class.forName (""). GetConstructor (String.class); Create an Instance object Obj=constructor.newinstance ("abc");     Constructor Constructor Method: Represents a constructor method in a class. Get all the constructs in a classMethod Constructor constructors[]= Class.forName (""). GetConstructors ();          Get a constructor method Constructor constructor= Class.forName (""). GetConstructor (Stringbuffer.class);     Constructor constructor= Class.getconstructor (stringbuffer.class);          Create an Instance object string str= (String) constructor.newinstance (new StringBuffer ("abc")); Call the obtained method using the same type of instance object above Class.newinstance () method: String obj= (String) class.forname ("java.lang.String"). Newinsta            NCE (); The default constructor is obtained first, and then the instance object is created with this construction method.  The member variable filed class reflects a class that represents a member variable in a class.   Reflectpoint pt1=new Reflectpoint (3,5); Filed filedy=pt1.getclsss (). getfiled ("Y"), or//only represents which object Filed filedy=pt1.getclsss (). Getdeclaredfield ("x")// Gets whether the object is private or protected filedy.setaccessible (TRUE);//settings can be accessed, violent reflection filedy.get (PT1)//Remove the value of Y to turn B in the field into a field[] Fields=obj.getcl GetFields ().//Get all objects for (Field field:fields) {if (Field.gettype () ==string.class) {///if string Dvalue = (string) field.get (obj);//Get string Contents StrinG NewValue = Oldvalue.replace (' B ', ' a '); replaces the string contents with Field.set (obj,newvalue); assigns the new value to the reflection of the Object method class member methods.     Gets the member method reflection form: Method Methodcharat = String.class.getMethod ("charAt"-method name, int.class--this is the parameter type, if the null parameter function is NULL);          Object obj=clazz.newinstance ();  Methodcharat.invoke (str1,1);     The Reflection Class Clazz=obj.getclass () of the array;     if (Clazz.isarray ()) {int len=array.getlength (obj); for (int i=0;i<len;i==) {soparray.get (obj,i)}} The reflection to get the generic information by specifying the corresponding class object, the program can get all the field in that class, regardless of the Field uses private method public. You can use GetType () to obtain the type of a Field object after it has been obtained. class<?> type = F.gettype ();//Gets the types of fields but this method is only valid for normal field, if the field has a generic decoration, it is not accurate to obtain the field's generic parameters, such as Map<string,integer >; in order to obtain a generic type for the specified field, we adopt: type GType = F.getgenerictype (), get the generic type and then strongly convert the type object to Parameterizedtype, which means that the type after the generics is incremented Getrawtype ()//returns the type that is restricted by the generic type; Type[] getactualtypearguments ()//return generic parameter type; Use reflection to get generic type (generic information) step: Gets the current class gets the target field gets the type that contains the generic type Getgenerictype () Strong go to subclass Parameterizedtype because the type does not have any corresponding method to get the generic type getactualTypeArguments () example 
1  Packagejunereflect624;2 3 ImportJava.lang.reflect.Field;4 ImportJava.lang.reflect.ParameterizedType;5 ImportJava.lang.reflect.Type;6 ImportJava.util.HashMap;7 ImportJava.util.Map;8 9  Public classGetGenericTypeDemo14 {Tenmap<string,integer> map =NewHashmap<string,integer>(); One      A      Public Static voidMain (string[] args)throwsException { -Class C = GetGenericTypeDemo14.class; -Field f = C.getdeclaredfield ("Map"); the System.out.println (f); -System.out.println (F.getname ());//Map -          -         //class<?> GetType () returns a Class object that identifies the claim type of the field represented by this Field object.  +Class cl =F.gettype (); -SYSTEM.OUT.PRINTLN ("Get its type:" +cl); + //get the type: interface Java.util.Map A          at         /** - * Type Getgenerictype () returns a Type object that represents the declared type of the field represented by this Field object.  - * Type is the interface of class; -          */ -Type t = F.getgenerictype ();//the type that contains the generic type - System.out.println (t); in //java.util.map<java.lang.string, java.lang.integer> -          to  +         /** - * Type This class does not have any method, so need to call the method of the subclass, then the big type goes to the small type, need to strong turn!  the          */ *Parameterizedtype pt = (parameterizedtype) t;//strong go to its child class $         /**Panax Notoginseng * type[] getactualtypearguments () - returns an array of type objects that represent the actual type parameters of this type.  the Type Getownertype () + returns a type object that indicates that the type is one of its members.  A Type Getrawtype () the returns a Type object that represents a class or interface that declares this type.  +          */ -          $t = Pt.getrawtype ();//class or interface of type $ System.out.println (t); -          -type[] ts =pt.getactualtypearguments (); the          for(Type type:ts) { - System.out.println (type);Wuyi             /** the * Class Java.lang.String - class Java.lang.Integer Wu              */ -         } About     } $}

Print: Java.util.Map junereflect624. Getgenerictypedemo14.mapmap gets its type: interface java.util.mapjava.util.map<java.lang.string, java.lang.integer> Interface Java.util.Mapclass Java.lang.Stringclass Java.lang.Integer My summary: Find more APIs, refer to the restrictions used by methods in the API, such as whether static, return value type, etc.

Dark Horse programmer--java Basics-Reflex

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.