The reflection of Java

Source: Internet
Author: User

March 11, 2017 Saturday Sunny

The understanding of Java reflection can better understand the operation mechanism of spring.

Because spring's two core technologies are the IOC (inversion of control, inversion of controls, sometimes also called dependency injection, i.e. Di,dependcy injection) and AOP (Aspect oriented programming, Aspect-oriented programming, i.e. portrait programming). The IOC implementation principle is the Java reflection mechanism, and the AOP implementation principle is the dynamic agent of Java.

   The concept of the reflection mechanism in Java:

The reflection mechanism of Java is in the running state, and for any class, all the properties and methods of the class can be known, and any one of the objects may be called with any of its methods and properties. This dynamic access information and dynamic Call object method is the reflection mechanism of java.

the Java reflection mechanism mainly provides the following functions

1 determine the class to which any object belongs at run time

2 constructing an object of any class at run time

3 Determining the member variables and methods that any one class has at run time

4 in Run is a method of invoking any object

5 Generating dynamic agents

In the JDK, Java's reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package.

Class: Represents classes and interfaces in a running Java application. Class is the most important feature class in Java reflection, and all of the object information (including methods, construction methods, access rights) is implemented by it.

Field: Provides information about the properties of a class or interface, and the dynamic access rights to it

Constructor: Provides information about a single construction method of a class and access to it

Method: Provides information about one of the methods in a class or interface

Array class: Provides dynamic creation of arrays, and static methods for accessing array elements

The GetClass () method is defined in the Java.lang.Object class, so the object type can be obtained by this method for any Java object.

Class is the core class in the reflection API, and it has the following methods:

1 Getting the object type

A getName (): Gets the full name of the class

b getfields (): Gets the properties of the public type of the class

C Getdeclarefields (): Get all the properties of a class

D GetMethods (): Method for obtaining the public type of a class

E getdeclaredmethods (): Gets all the methods of the class

F GetMethod (String name,class[] parametertypes): Gets the specific method of the class, the name parameter specifies the method's first names, and the Parametertypes parameter of the constructor method.

G Getconstrutors (): How to get the public type of a class

H newinstance (): Creates an object of this class by constructing a class without parameters

2 Creating a new object with the default construction method

Object objectcopy=classtype.getconstructor (New class[]{}). newinstance (New object[]{});

This code first calls the class GetConstructor () method to get a constructor object that represents the default construction method, and then calls the constructor object's Newinstance () method to construct an instance

3 Getting all the properties of an object

Filed Fileds[]=classtype.getdeclarefields ();

The class Getdeclaredfields () method returns all properties of the class, including Public,protected,default (default) and private access level properties

4 Get the GetXXX () and Setxxx () methods for each property response, and then execute these methods to copy the properties of the original object into the new object. The typical code is as follows:

for (int i=0;i Field field=fields[i];

String Filedname=field.getname ();
String firstletter=fieldname.substring (0,1). toUpperCase ();

String getmethodname= "Get" +firstletter+fieldname.substring (1);//Get the GetXXX () method name corresponding to the property

String setmethodname= "Set" +firstletter+fieldname.substring (1);//Get the name of the Setxxx () method corresponding to the property

Method Getmethod=classtype.getmethod (Getmethodname, New class[]{});//Get and attribute corresponding GetXXX () methods

Method Setmethod=classtype.getmethod (Setmethodname, New Class[]{field.gettype ()});//Get and attribute corresponding Setxxx () methods

Object Value=getmethod.invoke (Object,new object[]{});//Call the original object's GetXXX () method

System.out.println (fieldname+ ":" +value);

Setmethod.invoke (Objectcopy,new object[]{value});

The Invoke of method Class (Object Obj,new object args[]) methods must be converted to an object of the corresponding wrapper type if the parameter must be an object of the underlying type data.

The return value of the Invoke () method is always the object, and if the return value type of the method that is actually called is the base type data, then the Invoke () method converts it to the corresponding packet-to-class object and returns it

The Java.lang.Array class provides a variety of static methods for dynamically creating and accessing array elements. The main () method of the ArrayTester1 class of the code below creates a string array of length 10, then sets the element with index position 5 to Hello, and then reads the value of the element at index position 5.

import Java.lang.reflect.Array; Public classArrayTest1 { Public Static voidMain (string[] args) throws Exception {Class ClassType= Class.forName ("java.lang.String"); //create a string array of length 10Object array = array.newinstance (ClassType,Ten); //set the element with index position 5 to HelloArray.Set(Array,5,"Hello"); //reads the value of an element with an index position of 5string s = (string) Array.Get(Array,5); System. out. println (s); }}
View Code

    

    A simple example of application of Java reflection mechanism

    Example 1: Get the full package name and class name from the object

Package qianyu.com;classhello{ Public voidsay () {System. out. println ("Hello,everyone"); }} Public classDemo1 { Public Static voidMain (string[] args) {Demo1 demo=NewDemo1 (); System. out. println ("Demo:"+Demo.getclass ()); System. out. println ("Demo:"+Demo.getclass (). GetName ()); Hello Hello=NewHello (); System. out. println ("Hello:"+Hello.getclass ()); System. out. println ("Hello:"+Hello.getclass (). GetName ()); }}
case1

The results of the operation are as follows:

Demo:class Qianyu.com.Demo1
Demo:qianyu.com.Demo1
Hello:class Qianyu.com.Hello
Hello:qianyu.com.Hello

As shown above: through the reflection mechanism of Java, you can get the complete path of the object in the process of running, in fact, all classes in Java objects are actually instances of class

Example 2: Instantiating class object

Package qianyu.com;classhello1{ Public voidsay () {System. out. println ("Hello,everyone"); }} Public classDemo2 { Public Static voidMain (string[] args) {Class<?> demo1=NULL; Class<?> demo2=NULL; Class<?> demo3=NULL; Class<?> demo4=NULL; Try{demo1= Class.forName ("Qianyu.com.Demo2"); } Catch(ClassNotFoundException e) {e.printstacktrace (); } Demo2=NewDemo2 (). GetClass (); Demo3=hello.class; Demo4=hello1.class; System. out. println ("Demo2 class name in this code"+demo1.getname ()); System. out. println ("Demo2 class name in this code"+demo2.getname ()); System. out. println ("the Hello class name in the same package"+demo3.getname ()); System. out. println ("Hello1 class name in this code"+demo4.getname ()); }}
Case2

The results of the operation are as follows:

The Demo2 class name in this code QIANYU.COM.DEMO2
The Demo2 class name in this code QIANYU.COM.DEMO2
Hello class name Qianyu.com.Hello in the same package
The Hello1 class name in this code QIANYU.COM.HELLO1

  

    

The reflection of Java

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.