Class object and the learning of reflection mechanism

Source: Internet
Author: User

Just learned about the Java reflection mechanism and made a summary here.

The summary is divided into three parts, one. Introduces the class concept of Java, two. Further introduction through class we can get what information about the class, three. Basic operation of Reflection method

Before that, we must keep in mind the following sentence: "All things are objects!" "This phrase can always be used throughout this section to help us to stand a high understanding of this part of the content.

I. Java class concept

Everything is object, then for the object-oriented language Java, we can naturally add the next sentence, everything has a class, because each object instance has the category he belongs to.

So for the string in our code, Date,time type, or our custom demo class, these classes are also an object in a different perspective, and these special objects belong to the class category. (Note: Full path is Java.lang.Class)

Class objects, which are instantiated by class classes, have their own class objects defined for each class in Java, and the class object contains some information about the class and how to do it.

Here we distinguish between the two concepts, "class objects" and "Objects of class", the former is studied in this chapter, and examples of string classes are given to illustrate:

  

// Str is a string "Object of Class" Class C = String. class // C is the "class object" of String

After defining the concept of the class object, let us explain how we get the class object. We create a class Demotest under package com.classtest, so there are three ways to get its class object.

  

        //the first way to get a class object (by Class)Class C1 = demotest.class; //the second way to get the class object (through the class instance)Demotest dt =Newdemotest (); Class C2=Dt.getclass (); //The Third way to get the class type, which requires catching exceptions, is to dynamically load the core method of the classClass C3 =NULL; Try{C3= Class.forName ("Com.classtest.DemoTest"); }Catch(ClassNotFoundException e) {e.printstacktrace (); }            

In particular, in the first two methods, Java at compile time needs to detect the Demotest class already exist, or compile errors, and the third method of obtaining class objects, Only at run time will judge the use of the Com.classtest.DemoTest class exists, or error, and therefore need to add an abnormal judgment. Note that the third method is the core method of implementing the dynamic load class, since it is not possible to determine which class's class object is obtained at run time.

Two. Information we can get through class objects

If we get the class object of a class, then we can use it to get an instance of this class, the class name of the class, this class contains the method name, the member variables of this class, the constructors of this class, and so on rich information. This is explained below.

1) Obtain an instance of the class based on the class object of the class

    

Try {  // call the Newinstance () method of the class object to get the instance DT1, note the need to force type conversions            Demotest dt1 = (demotest) c3.newinstance ();            Dt1.show ();
Note Catch Exception }catch(instantiationexception e) { e.printstacktrace (); } Catch (illegalaccessexception e) { e.printstacktrace (); }

2) Get the class name of the class based on the class object

// calling the GetName method of a class object Class C = demotest. class ; String className = C.getname ());

3) method of obtaining the class based on the class object

All things are objects, methods are objects, and they belong to the type Java.lang.reflect.Method

A static method is defined here, and the parameter is an object that returns the methods contained by the class to which the object belongs.

/** Print the name of the class, method information of the class * method is also an object, the class of the method object is Java.lang.reflect.Method * @param ob object of the class being tested*/     Public Static voidgetclassmethods (Object ob) {Class C=Ob.getclass ();
The GetMethods method of the class object returns an array of class-containing method objects method[] Methods=C.getmethods (); System.out.println ("The class name of the current class is:" +c.getname ()); System.out.println ("The class exposes methods are:"); for(inti=0;i<methods.length;i++){ //get the name of the methodSystem.out.print (Methods[i].getname () + "("); //get the parameter name of the methodclass[] Paramtypes =methods[i].getparametertypes (); for(Class pt:paramtypes) {System.out.print (Pt.getname ()+","); } System.out.println (")"); } }

4) Get the member variables that the class contains based on the class object

Everything is object, the member variable is also an object, and its type is Java.lang.reflect.Field

A static method is defined here, and the parameter is an object that returns the member variables contained in the class to which the object belongs.

/** The member variable of the print class * member variable is also an object, belongs to the Java.lang.reflect.Fild class * Fild class encapsulates operations on member variables * @param ob*/     Public Static voidGetclassfield (Object ob) {Class C=Ob.getclass ();
GetFile returns the member variable object data for a class//field[] fields = C.getfields ();field[] Fields =C.getdeclaredfields (); System.out.println ("The class name of the current class is:" +c.getname ()); System.out.println ("The member variables of the class are:"); for(Field field:fields) {//gets the class type of the member variableClass ftype =Field.gettype (); String ClassName=Ftype.getname (); String FieldName=Field.getname (); System.out.println (ClassName+" "+fieldName); } }

5) How to construct the corresponding class based on the class object

Everything is object, and the construction method is also the object, which belongs to the type Java.lang.reflect.Constructor

A static method is defined here, and the parameter is an object that returns the construction method contained by the class to which the object belongs

/** Get information about all constructors for a class * constructors are also objects, constructors belong to class Java.lang.reflect.Constructor * @param ob*/     Public Static voidgetconstructors (Object ob) {Class C=Ob.getclass (); Constructor[] Cons=c.getdeclaredconstructors (); System.out.println ("The class name of the current class is:" +c.getname ()); System.out.println ("Class is constructed by:");  for(inti=0;i<cons.length;i++){            //get the name of the methodSystem.out.print (Cons[i].getname () + "("); //get the parameter name of the methodclass[] Paramtypes =cons[i].getparametertypes ();  for(Class pt:paramtypes) {System.out.print (Pt.getname ()+","); } System.out.println (")"); }    }

Three. Basic operation of Method reflection

The second part shows that through the class object we can get a series of information about the class, this section we describe the method of invoking the class by getting the method object information.

Reflection here involves two questions 1. How to obtain a specific method object 2. How the class is called by Method objects.

1. Get a specific Method object

First we define two methods in a custom type Demotest class.

  

// define a non-parametric method show  Public void Show () {        System.out.println ("This is a demotest"    ); // defines a method for an argument add     Public int Add (int A,int  b) {        return a +b;    }  

Then get the class object of the class, the Class object has method GetMethod can get the specified method object, as shown in the following code:

Class C = demotest. class // get the No-reference method show Method m1 = C.getmethod ("show"); // get a method add int. class,int. class);

2. By invoking a method on a method object, the Invoke method of the method object can call the corresponding method, noting that getting the method object and the call can throw an exception, so the merge is written as follows:

Try{Class C= Demotest.class; //get the No-reference method showMethod m1 = C.getmethod ("Show"); //get a method addMethod m2 = C.getmethod ("Add",int.class,int.class); Demotest demotest=Newdemotest (); //invoke method to invoke, need to pass an instance demotestM1.invoke (demotest); Object result= M2.invoke (demotest, 2,3);        SYSTEM.OUT.PRINTLN (result); } Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); }            

This completes the method that is called by the method object reflection call.

Own understanding: The programmer through the class object, the method object, the member variable object, constructs the method object and so on the procedure operation behavior, relative to the class, the method, the member variable, constructs the method, is the reflection operation. The reflection operation has skipped the Java code, which is similar to the compiled. Class code, so that reflection-related programs can dynamically load some resources, and report errors only when the runtime looks for the existence and reasonableness of the use of the resource.

Class object and the learning of reflection mechanism

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.