JAVA reflection mechanism

Source: Internet
Author: User

First, what is reflection

The concept of reflection was first proposed by Smith in 1982 , a capability that a program can access, detect, and modify its own state or behavior.

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; This dynamic access to information and the ability to dynamically invoke object methods, called Java The reflection mechanism of language.

Second, the application of reflection

1.Spring frame:IOC(Control inversion)

2.Hibernate Framework: correlation mapping, etc.

3. White Box test

Third, the relevant API

1.java.lang under the bag

Class<t>: represents a class and interface in a running Java application, and is the origin of Reflection.

2.java.lang.reflect under the bag

Field class : represents a member variable of a class, also called a property of a class.

Method Class : methods that represent classes.

Constructor class : represents the construction method of a class.

Array class : provides a static method for dynamically creating arrays and accessing array elements.

Iv. about class<t>

A class is part of a program, and each class has an object of class . In other words, whenever a new class is written and compiled, a class object is generated .

Class has no public constructor method. Class objects are constructed automatically by the Java virtual machine when the class is loaded and by invoking the DefineClass method in the ClassLoader , so you cannot explicitly declare a class object.

Class is the origin of Reflection. To manipulate the properties and methods in a class, you must start by getting the class Object and get the following table.

How to get

Description

Example

Object.getclass ()

Gets the Class of the specified instance object

List li = new ArrayList ();

Class Licla = Li.getclass ();

Class.getsuperclass ()

Gets the inheritance class class for the current class

List li = new ArrayList ();

Class Licla = Li.getclass ();

Class Sucla = Licla.getsuperclass ();

Object.class

. class Direct Access

Class LICLA = Arraylist.class;

Class.forName (" class name ")

Using the static method of class, passing in the full name of

Class CLA = Class.forName ("Java.util.ArrayList");

Primitive.type

The wrapper class for the base data type gets the class way

Class longclass = Long.type;

Class inteclass = Integer.type;

V. Use of Reflection

creates a target for the reflection operation.

 Package reflection;  Public class baseuser {    private  String BaseID;      Public String Getbaseid () {        return  baseid;    }      Public void Setbaseid (String baseid) {        this. BaseID = BaseID;    }} 
Baseuser class
 Packagereflection; Public classUserextendsBaseuser {PrivateString ID;  PublicString name;  PublicUser () {} PublicUser (String name) { This. Name =name; }     PublicString getId () {returnID; }     Public voidsetId (String id) { This. ID =ID; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }}
user class, inheriting Baseuser
 Package reflection;  Public class Reflection {    public  String pubfield;          Public void test1 () {                System.out.println ("This is a public method! ");    }      Public void test2 (String test) {                System.out.println ("This is a parameter public  method! Parameters are: "+ test);    }    }
Reflection Class

(a) instantiating an object by reflection

1. instantiate an object without a parameter constructor.

2. instantiate the object with the parameter constructor.

 Packagereflection; Public classDemo { Public Static voidMain (string[] args) {Class<?> CLA = User.class; Try{User u1=(User) cla.newinstance (); System.out.println ("Instantiate an object without a parameter constructor, one way:" +U1); User U2=(User) Cla.getconstructor (). newinstance (); System.out.println ("Instantiate an object without a parameter constructor, mode two:" +U2); User U3= (User) cla.getconstructor (String.class). newinstance ("Ginseng"); System.out.println ("Instantiate an object with a parameter constructor:" + U3 + "Name:" +u3.getname ()); User U4=NewUser (); System.out.println ("Frequently instantiated objects:" +U4); } Catch(Exception e) {e.printstacktrace (); }    }}
Demo Class

(b) call Method by Reflection

 Packagereflection;ImportJava.lang.reflect.Method; Public classRefmethodtest { Public Static voidMain (string[] args)throwsexception{Class<?> clazz = Reflection.class; Object obj=clazz.newinstance (); System.out.println ("Obtain the specified method as declared by the current class, Test1 ():"); Method M1= Clazz.getdeclaredmethod ("Test1"); System.out.println ("Method name is:" +m1.getname ()); System.out.println ("Run this method:");                M1.invoke (obj); System.out.println ("Get the specified method declared by the current class, Test2 ():"); Method m2= Clazz.getdeclaredmethod ("Test2", String.class); System.out.println ("Method name is:" +m2.getname ()); System.out.println ("Run this method"); M2.invoke (obj,"This is the parameter"); }}
Refmethodtest class

(c) calling Field by Reflection

 Packagereflection;ImportJava.lang.reflect.Field; Public classReffieldtest { Public Static voidMain (string[] args)throwsexception{Class<?> clazz = Reflection.class; Object obj=clazz.newinstance (); System.out.println ("To obtain the properties specified by the current class and the superclass, Pubfield:"); Field F= Clazz.getdeclaredfield ("Pubfield"); System.out.println ("Property Name:" +f.getname ()); System.out.println ("Dynamically set the value of field by reflection"); F.set (obj,"New Value"); System.out.println ("Get the value of field dynamically by reflection"); System.out.println (The value of field is: "+f.get (obj)); }}
reffieldtest

JAVA 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.