Dark Horse Programmer--high-tech---reflection

Source: Internet
Author: User

Dark Horse Programmer--high-tech---reflection

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

I. Overview

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.

Reflection maps the various components of a Java class to the corresponding Java classes, such as a class of objects in a Java class that is represented by an object, a component of the classes: member variables, methods, construction methods, packages, and so on, which are represented by a Java class. The class class of Java is to provide a series of methods to obtain the variables, methods, construction methods, modifiers, packages and other information, which is represented by the corresponding instance object of the class, they are field, method, Contructor, package and so on.

Second, the text

1 , Class class

the class class of Java is the basis of the Java reflection mechanism, and we can obtain information about a class through class classes. Virtual machines manage a unique class object for each type. In other words, each class (type) has a class object. When you run the program, the Java Virtual Machine (JVM) first checks to see if the class object for the classes that you want to load is already loaded. If it is not loaded, the JVM will look up the. class file based on the class name and load its class object.

Here are three ways to get a class object:

    1. Use the GetClass () method of the object class to get the class object, which is also the most common way to produce a class object. Example: Class C1 = X.getclass ();
    2. Use the forname () method in the class class to get the class object that corresponds to the string. Example: Class C2=class.forname ("The full class name of a class")
    3. The third method of getting a class type object is very simple. If T is a Java type, then T.class represents the matching class object. For example: Class Cl2 = Int.class;

Here are the methods of the Cl14ass class:

1. public static class<?> forname (String className): Natice method, dynamic load class. Very important 2. Public T newinstance (): Creates a new object based on the object's class for reflection. Very important 3. Public ClassLoader getClassLoader (): Gets the class loader 4. Public String getName (): Gets the name of the class or interface 5. Public native Class Getsuperclass (): Gets the parent class of the class, inherits the parent class, returns the parent class, or returns 6. Public Java.net.URL getresource (string name): Gets the resource 7 based on the string. public boolean isenum (): Determines whether enumeration is of type 8. Public native Boolean IsArray (): Determines whether the array type is 9. Public native Boolean isprimitive (): Determines whether the base type is 10. public native int getmodifiers (): Get modifier 11 in reflection. public field GetField (String name): Gets the domain member 12 in reflection. Public field[] GetFields (): Gets the domain array member 13. Public method[] GetMethods (): Get method 14. Public constructor<?>[] GetConstructors (): Get all constructors

  

2 , Constructor class

The Constructor class is a reflection class that constructs methods for various classes. Constructor the acquisition of a reflection class object, for example:

Constructor Constructor=string.class.getconstructor (Stringbuffer.class);

A construction method can be used to construct an instance object, for example:

String str= (String) constructor.newinstance (new StringBuffer ("abc"));

The class itself also has the Newinstance method, which can be called directly, for example:

String obj= (String) String.class.newInstance (); is similar to calling an argument-free construction method.

Here's a simple example code:

//to create a class instance method by using the constructor object Public Static voidConstructordemo () throws exception{//gets the class object for test classesString ClassName="cn.itheima.Test"; Class Clazz=Class.forName (className); //gets the class instance of the specified constructorConstructor con= Clazz.getconstructor (String.class,int.class); Test P= (Test) con.newinstance ("Lisi", -); System. out. println (P.tostring ());}

3 , Filed class

Java uses the getfileds () or GetField () method of a class object to get all the field or specified filed that the class contains. Here are two ways to read or set the value of field:

1. GetXxx (Object obj): Gets the property value of the field of the Obj object. Here xxx corresponds to 8 base types, and if the type of the property is a reference type, then the xxx after get is canceled. 2. Setxxx (Object obj,xxx val): Sets the field of the Obj object to a Val value. Here XXX corresponds to 8 basic types, if the type of the property is a reference type, after canceling set XXX.

Here's a simple example code:

 Public classTest { PublicFinalintA=5;  Public Static voidMain (string[] args) {test test=NewTest (); Try {                        //Specifies the name of the field to getField Field= Test.class. GetField ("a"); //gets an integer value from the test object;System. out. println (Field.getint (test)); //If you are not sure what data type can return an objectObject obj= field.Get(test); System. out. println (obj); //gets the data type of the objectSystem. out. println (Obj.getclass (). GetName ()); } Catch(Exception e) {e.printstacktrace (); } }}

4 , manipulating arrays

An array class is provided under the Java.lang.reflect package, and the array object can represent all arrays. Programs can create arrays dynamically by using array, manipulate array elements, and so on. Array provides the following types of methods:

Static Object newinstance (class<?> componenttype,int...length): Creates a new array 2 with the specified element type and the specified dimension . Static xxx getXxx (Object array,int index): Returns the index element of the array. where xxx is a variety of basic data types, if the array element is a reference type, then the method becomes       get (Object array,int  index)staticvoid setxxx (Object array,int index,xxx val): Sets the value of index element in array array to Val. where xxx is a variety of data types, if the array element is a reference class         , then the method becomes set (Object array,int index,xxx val)

The following is a piece of code: print an incoming object, print directly if it is a single object, and print the array element one at a time, if it is a group object (applies to the judgment of the arrays)

 public  void   PrintObject (Object obj) {Class cla  = if   (Cla.isarray ()) { int  len=array.getlength (obj);  for  (int  i= 0 ; I<len;i++) {System.  out . println (Array.  (Obj,i)); }}  else  {System.  out       .println (obj); }}

5 , Method class

When you get the Clss object for a class, you can get all methods or methods (the return value of both methods as an array of method) or method object through the class object's GetMethods () method or the GetMethod () method.

Here's how:

// get only methods in public and parent classes // gets the class that contains the private 3.  method GetMethod ("Methods name", parameter. ) Class(null if null))// The method obj is the keynote that executes the method, followed by the argument

Here's a sample code: Get one of the methods in the class.

 Public classreflectmethod{ Public Static voidMain (String args[])throwsexception{//new String[]{new string ("abc"), New String ("XYZ"), New String ("MN")};//string Array//New Object[]{new String ("abc"), 1};//Object ArrayString str1= "ABCD"; //Str1.chatat (1);Method Methodcharat= String.class. GetMethod ("CharAt",int.class); Charc = (Character) methodcharat.invoke (STR1,NewObject[]{2}); //using the jdk1.4 syntax call, pass an object array inSystem.out.println (c);//C    }}

Iii. Summary

This article simply describes the basic concepts of reflection, as well as the three ways to get the underlying class of reflection and the common methods, as well as the simple application of four classes of filed, method, array, and constructor related to reflection.

Dark Horse Programmer--high-tech---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.