Java Foundation Consolidation--reflection

Source: Internet
Author: User
Tags modifier object object reflection

What is reflection

The reflection mechanism refers to the information that can be obtained when the program is run. In Java, as long as the name of the class is given, the information of the class can be obtained through the reflection mechanism.

Where to use the reflection mechanism

In JDBC, it is the reflection that is used to instantiate an object, such as: Class.forName ("Com.mysql.jdbc.Driver.class"). newinstance ();

The framework uses the reflection mechanism, spring,hibernate and struts are all implemented by reflection mechanism.

Advantages and disadvantages of the reflection mechanism

Why use a reflection mechanism? Creating objects directly doesn't make sense, it involves the concept of dynamic and static,
Static compilation: Determines the type at compile time, binds the object, which is passed.
Dynamic compilation: The runtime determines the type, binding object. Dynamic compilation maximizes the flexibility of Java and embodies many
To reduce the coupling of the classes.
In a word, the advantage of reflection mechanism is that it can realize dynamic object creation and compilation, which shows great flexibility, especially in the development of Java EE.

Its flexibility is very obvious. For example, a large-scale software, it is impossible to design the perfect one at a time, when the program compiled, released, when the discovery needs to update some features, we can not want users to uninstall the previous, and then reinstall the new version, if so, this software is certainly not many people use. Using static words, the entire program needs to be recompiled once to achieve the function of the update, and the use of reflection mechanism, it can not uninstall, only need to be dynamically created and compiled at runtime, you can achieve the work
Yes.
Its disadvantage is that it has an impact on performance. Using reflection is basically an interpretation operation, and we can tell the JVM what we want to do and it
To meet our requirements. This type of operation is always slower than just performing the same operation directly.

What can I do with the reflection mechanism?

Class c=class.forname ("ClassName"); Note: ClassName must be the full name, that is, include the package name, for example, Cn.netjava.pojo.UserInfo;
Object Obj=c.newinstance ();//Create an instance of an object

Get constructor

Constructor GetConstructor (class[] params)//Get public constructor based on specified parameters

Constructor[] GetConstructors ()//all constructors for public

Constructor getdeclaredconstructor (class[] params)//Get public and non-public constructors based on specified parameters

Constructor[] Getdeclaredconstructors ()//all constructors for public

Methods to get classes

Method GetMethod (String name, class[] params), obtained by method name, parameter type

Method[] GetMethods ()//Get all the public methods

Method Getdeclaredmethod (String name, class[] params)//Get public and non-public methods based on method name and parameter type

Method[] Getdeclaredmethods ()//get so public and non-public methods

Get the properties of a class

  Field GetField (String name)//Get the appropriate public variable based on the variable name

Field[] GetFields ()//Get the method of public in class

Field Getdeclaredfield (String name)//Get public and non-public variables by method name

field[] getdeclaredfields ()//Get all public and non-public methods in the class

working with Instances

Get class Properties:

 Public classTestgetfieldextendsObject {Private Static Final LongSerialversionuid = -2862585049955236662l;  Public Static voidMain (String args[])throwsException {Class<?> clazz = Class.forName ("reflect. Testgetfield "); System.out.println ("=============== This class property ==============="); //get this type of propertyfield[] Fields =Clazz.getdeclaredfields ();        GetField (fields); System.out.println ("========== implemented interface or parent class Property =========="); //gets the implemented interface or properties of the parent classfield[] Fatherfield =Clazz.getfields ();    GetField (Fatherfield); }     Public Static voidGetField (field[] fields) { for(Field field:fields) {//Permission Modifiers            intMo =field.getmodifiers (); String Priv=modifier.tostring (MO); Class<?> type =Field.gettype (); System.out.println (Priv+ "" + type.getname () + "" + field.getname () + ";"); }    }}

Get the method of the class:

 Public classTestgetmethodImplementsserializable{Private Static FinalString teststring= "Hello";  Public Static voidMain (String args[])throwsexception{Class<?> clazz = Class.forName ("reflect. Testgetmethod "); Method[] Methods=Clazz.getmethods ();  for(Method method:methods) {Class<?> ReturnType =Method.getreturntype (); Class<?> para[] =method.getparametertypes (); inttemp =method.getmodifiers ();            System.out.print (modifier.tostring (temp));            System.out.print (Returntype.getname ());            System.out.print (Method.getname ());  for(Class Par:para) {System.out.println (Par.getname ()); }                    }    }}

Instantiate class:

 Public classTestnewinstance { Public Static voidMain (string[] args)throwsexception{Class<?> Class1 =NULL; Class1= Class.forName ("reflect. User "); //the first method, instantiating the default constructor method, calls set assignmentUser User =(User) class1.newinstance (); User.setage (20); User.setname ("ADF");        SYSTEM.OUT.PRINTLN (user); //the second gets all of the constructors using constructors to assign values    }}classUser {Private intAge ; PrivateString name;  PublicUser () {Super(); }     PublicUser (String name) {Super();  This. Name =name; }     PublicUser (intAge , String name) {        Super();  This. Age =Age ;  This. Name =name; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; } @Override PublicString toString () {return"User [age=" + Age + ", name=" + name + "]"; }}

Ways to use classes:

 Public classTestusemethod { Public Static voidMain (string[] args)throwsexception{Class<?> clazz = Class.forName ("reflect. Testusemethod "); //calling the Reflect1 methodmethod = Clazz.getmethod ("Reflect1");        Method.invoke (Clazz.newinstance ()); //calling the Reflect2 methodmethod = Clazz.getmethod ("Reflect2",int.class, String.class); Method.invoke (Clazz.newinstance (),"Test"); }     Public voidReflect1 () {System.out.println ("Java reflection Mechanism-call Method 1 of a class."); }     Public voidReflect2 (intAge , String name) {System.out.println ("Java reflection Mechanism-call Method 2 of a class."); System.out.println ("Age--" + Age +. Name--"+name); }}

Dynamic Agent:

 Public classTestproxy { Public Static voidMain (String args[])throwsexception{Myinvocationhandler Demo=NewMyinvocationhandler (); Subject Subject= (Subject) demo.bind (Newrealsubject ()); System.out.println (Subject.say ("Janti", 20)); }}Interfacesubject{ PublicString say (string name,intAge );}//define a real projectclassRealsubjectImplementsSubject { PublicString say (string name,intAge ) {        returnName + "" +Age ; }}//If you want to complete a dynamic proxy, you first need to define a subclass of the Invocationhandler interface, and the agent has completed the specific operation. classMyinvocationhandlerImplementsinvocationhandler{PrivateObject object =NULL;  Publicobject bind (Object obj) { This. Object =obj; returnProxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), This); } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {Object temp= Method.invoke ( This. Object,args); returntemp; }}

Java Foundation Consolidation--reflection

Related Article

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.