The reflection mechanism in Java

Source: Internet
Author: User

First, what is reflection in Java:

Reflection is one of the characteristics of the Java programming language, which allows the running Java program to check itself, or "self-audit", and to directly manipulate the internal properties and methods of the program. This ability of Java is not used much in practical applications, but there is no such feature in other programming languages at all. For example, there is no way to get information about a function definition in a program in Pascal, C, or C + +.
Reflection is the key to Java being considered a dynamic (or quasi-dynamic) language, allowing the program to obtain the internal information of any known name class in the execution period Reflection APIs. What information he can get from the class.

When using JDBC to connect to the database, use a sentence class.forname ("Com.mysql.jdbc.Driver.class"). newinstance (); At that time did not know that this is reflection, do not know his specific meaning. Many development frameworks now use a reflection mechanism, and hibernate and struts are implemented using reflection mechanisms.

Second, the class in Java

ClassThere is no public constructor. Instead Class objects is constructed automatically by the Java Vsan as classes is loaded and by calls to the defineClassmethod in the class loader.

The Java documentation explicitly says that class does not have a common constructor, which is created by the JVM, so we don't have to bother.

So how do we get the class object instance, there are the following three ways.

 PackageCom.iip;classPerson {PrivateString name;//Name Property    Private intAge;//Age Property     Public voidsetName (String name) { This. Name =name; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {return  This. Name; }     Public intGetage () {return  This. Age; }     PublicString toString () {//Overwrite ToString () method        return"Name:" + This. Name + ", Age:" + This. Age; }}; Public classReflection { Public  Static voidMain (string[] args) {Class<?> C1 =NULL ; Class<?> C2 =NULL ; Class<?> C3 =NULL;//declaring a Class object//three different methods        Try{C1= Class.forName ("Com.iip.Person");//1, Class.forName (package name + class name) need to catch ClassNotFoundException exception}Catch(ClassNotFoundException e) {e.printstacktrace (); } C2= person.class;//2. Instantiate a class object by the name of theC3 =NewPerson (). GetClass ();//3, through the object. GetClass () Instantiates a class objectPerson per=NULL;//declaring a person object        Try{per= (person) c1.newinstance ();//instantiating an object by newinstance ()}catch (Instantiationexception e) {E.printstacktrace (); }catch (Illegalaccessexception e) {
E.printstacktrace ();
} per.setname ("Test");//Set namePer.setage (30);//Set AgeSystem.out.println (per);//content output, calling ToString () }}

CLASS1,CLASS2,CLASS3 is the object of class. All of the information for class X can be obtained from these objects. Include fields (representing the member variables of the Class), Methods (method representing the Class), Constructor (representing the constructor of the class)

In class, there are the following methods.

GetName (): Get the full name of the class, package name + class name

GetFields (): Gets the properties of the public type of the class

Getdeclaredfields (): Gets all the properties of the class.

GetMethods (): Method that gets the public type of the class.

Getdeclaredmethods (): Gets all the methods of the class.

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

GetConstructors (): Gets the construction method of the public type of the class.

GetConstructor (class[] parametertypes): Gets the specific constructor method for the class, and the Parametertypes parameter specifies the type of the parameter for the constructed method.

Getdeclaredconstructors (): Returns all constructors in the class, including private

Newinstance (): Creates an object of this class from the constructor of the class without parameters.

We can then instantiate the object of the person class directly through the Newinstance () method of the class's object C1.

 Public throws Instantiationexception,illegalaccessexception

Newinstance returns a generic, so we need to cast to the person type.

First, this method must require the existence of an parameterless constructor in the person class, because the newinstance of class does not accept arguments, if I join the constructor method in person

 Public  Person (String name,int.  ) {  this. SetName (name);  this. Setage (age);}

There is only one construction method in the class, there will be no parameterless construction method provided by default, and then the error will be run.

Second, if the constructor of a class is private, such as class, we still cannot instantiate its object.

If you want to use an acceptable parameter of the newinstance, you need to explicitly specify the constructor method to invoke, and pass the parameters, but in the actual development, the general use of reflection instantiation, it is better to have a parameterless constructor, so it is more reasonable.

Gets the constructor for the person class constructor<?> cons[] = c1.getconstructors ();

constructor<?> cons[] =c1.getconstructors (); Person per=NULL;//declaring a person object        Try{per= (person) cons[0].newinstance ("test", 30);//instantiating an object}Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); }Catch(instantiationexception e) {e.printstacktrace (); }Catch(illegalaccessexception e) {e.printstacktrace (); }

Here's how to get all the fields of the person class.

Field [] f =C1.getdeclaredfields ();  for(inti = 0; i < f.length; i++) {Class<?> r = F[i].gettype ();//Get attribute Type            intMo = F[i].getmodifiers ();//get the number of modifiersString priv = modifier.tostring (MO);//Restore modifierSystem.out.print (Priv + "") ; System.out.print (R.getname ()+ " ") ;//Get attribute TypeSystem.out.print (F[i].getname ());//Output Attribute nameSystem.out.println (";") ; }

The output is:

Private java.lang.String name; Private int age;

Call the GetFields () method if you want to get only public properties.

Where in the JAVA reflection mechanism, field's GetModifiers () method returns an int that represents the modifier for the field.

The modifier is a static property of the Java.lang.reflect.Modifier.

The corresponding table is as follows:


Public:1
Private:2
Protected:4
Static:8
Final:16
Synchronized:32
Volatile:64
transient:128
native:256
interface:512
abstract:1024
strict:2048

Here's how to get a method in the person class

Method m[] = C1.getdeclaredmethods ();//get all the way         for(inti=0;i<m.length;i++) {Class<?> r = M[i].getreturntype ();//get the return value typeclass<?> p[] = M[i].getparametertypes ();//gets the type of all parameters            intxx = M[i].getmodifiers ();//Get modifierSystem.out.print (modifier.tostring (XX) + "");//output ModifierSystem.out.print (R + "") ;            System.out.print (M[i].getname ()); System.out.print ("(") ;  for(intj=0;j<p.length;j++) {System.out.print (P[j].getname ()+ "+" + "arg" +j); if(j<p.length-1) {System.out.print (",") ; }} Class<?> ex[] = M[i].getexceptiontypes ();//Remove Exception            if(ex.length>0) {System.out.print (") throws") ; }Else{System.out.print (")") ; }             for(intj=0;j<ex.length;j++) {System.out.print (Ex[j].getname ()); if(j<p.length-1) {System.out.print (",") ;        }} System.out.println (); }

Output to

 Public class java.lang.String toString ()  Public class java.lang.String getName ()  Public void setName (java.lang.String arg0)  Public void setage (int  arg0)publicint getage ()

Call the GetName method in the person class to

Method method =NULL ; Try{method= C1.getmethod ("GetName"); Try{Object name=Method.invoke (per);            SYSTEM.OUT.PRINTLN (name); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); }

To invoke a method with parameters

Method method =NULL ; Try{method= C1.getmethod ("SetName", String.class); Try{Method.invoke (per,"Java-java");            System.out.println (Per.getname ()); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); }

This is the end of basic learning this morning. There are many other methods in the class class in the Java documentation. Follow up on your studies.

Iii. Summary

Obviously the friends who have learned spring must understand why we can get the specified methods and variables through the configuration file, when we create the object by passing in the string implementation, as if you need anything, we go to produce for you, and we have been using object, This illustrates the dynamic nature of the Java language, and the dependency is greatly reduced.

The reflection mechanism in 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.