A gradual understanding of java--reflection

Source: Internet
Author: User

The effect of introducing reflection into layers

I. The concept of class types: All classes are objects and are instance objects of the class class, which we become class types

1. The following is a small test to produce the class type in 3 ways:

 Public classTest {/**     * @paramargs*/     Public Static voidMain (string[] args) {Foo user =Newfoo (); //Any class contains an implied static member variable classClass C1 = foo.class;Class C2 =User.getclass ();Class C3=NULL; Try{C3= Class.forName ("Test.foo"); } Catch(ClassNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
        C1 C2,C3 is the class type of the Foo class
}
Classvoid  print () {System.out.println ("haha");}}

2. The data type also has its own class type

  int. class; // class type  of int Class Class2 = String. class ;  double. class ;  Class class4 = Double. class ;   System.out.println (Class1);   System.out.println (Class2.getsimplename ());   System.out.println (CLASS3);  System.out.println (CLASS4);

3. Class types can create instance objects of a class

Try {    = (foo) c1.newinstance ();  The class type can create an instance    object of the class // A construction method      catch that requires no arguments ( Instantiationexception e) {    //  TODO auto-generated catch block      Catch (illegalaccessexception e) {    //  TODO auto-generated catch block     E.printstacktrace ();}

Two. Dynamic Load class

1. We have this confusion, if there are many classes in a main function, one of which has an error, the other classes are useless, so we think we want to use that class to let that class run, and do not want to recompile the main class, when the dynamic loading class comes in handy, There is a problem like this when you don't need a dynamic class:

Of course, this only happens when we manually use Javac compilation, and the development tools let us not see the details of these things.

2. We first draw the concept of dynamic load class, Class.forName ("") is a dynamic load class, and new Class () is a static load class, the essential difference is that when the static load class, the compile-time class must exist, and the dynamic load class does not necessarily exist.

 Public class Sum {    publicstaticvoid  main (string[] args) {        try         {            // Dynamic load class             //Args[0] represents the first parameter passed in the Main method             Class C = class.forname (args[0]);        }         Catch (Exception e)        {            e.printstacktrace ();     }}}

Three. Class-To-class operations

1. Get member methods by method class

/*** Get Member Methods * Method Class, Methods Object * A member method is a Methods object * the GetMethods () method gets all of the public functions, including inherited by the parent class * Getdeclar Edmethods () Gets all the methods that the class declares itself, without asking for access rights *@paramobj*/     Public Static voidprintclassmessage (Object obj) {Class C1=Obj.getclass ();        System.out.println (C1.getname ()); Method[] Ms= C1.getmethods ();//c.getdeclaredmethods ()         for(inti = 0; i < ms.length; i++) {            //gets the class type of the return value type of the methodClass ReturnType =Ms[i].getreturntype (); System.out.print (Returntype.getname ()+""); //get the name of the methodSystem.out.print (Ms[i].getname () + "("); //gets the parameter type---> Gets the class type of the type of the parameter listclass[] Paramtypes =ms[i].getparametertypes ();  for(Class class1:paramtypes) {System.out.println (Class1.getname ()); } System.out.println (")"); }            }

2. Get member variables by field class

/*** GET member Variable * member variable is also object * Java.lang.reflect.Field * filed class encapsulates operations on member variables * getfileds () method gets all the public's The information of the member variable * getdeclaredfiled Gets the information of the members variable that the class declares itself *@paramobj*/     Public Static voidprintfieldmethod (Object obj) {Class C1=Obj.getclass (); Field[] FS=C1.getdeclaredfields ();  for(Field field:fs) {//the class type that gets the type of the member variableClass FieldType =Field.gettype (); String TypeName=Fieldtype.getname (); //get the name of the member variableString fieldname=Field.getname (); System.out.println (TypeName+" "+fieldName); }    }

3. Get the constructor from the constructor class

/*** Information about the constructor of the Print object * information for the constructor is encapsulated in Java.lang.Constructor * GetConstructors gets all the public constructors * getdeclaredcons Tructors get all the constructors *@paramobj*/     Public Static voidprintconmessage (Object obj) {Class C=Obj.getclass (); //Constructor cs = c.getconstructors ();Constructor[] cs =c.getdeclaredconstructors ();  for(Constructor constructor:cs) {System.out.println (Constructor.getname ()+"("); Class[] Paramtypes=constructor.getparametertypes ();  for(Class class1:paramtypes) {System.out.println (Class1.getname ()+","); } System.out.println (")"); }    }

Four. Reflection

1. The function of reflection is to specify method name call method, the demo is as follows:

 Public classDemo { Public Static voidMain (string[] args) {//to get information about a class, you first get the class type of the classA A1 =NewA (); Class C1=A1.getclass (); /** Get method, name and parameter list to determine * GetMethod get public method * Getdelcaredmethod Gets the method that declares itself * */        Try{Method Method= C1.getmethod ("Print",int.class,int.class); /** Method of reflection Operation * A1.print (10,20); The reflection operation of the method is the same as the effect of the method call and the A1.print call with the M object * method How no return value is returned nul L, return value returns a specific return value * ... Indicates that several parameters are passed*/Object Object=method.invoke (A1, 10,20); Method method2=c1.getmethod ("Print",NewClass[]{string.class, String.class}); Method2.invoke (A1,"Hello", "World"); Method method3=c1.getmethod ("Print",NULL); Object a=Method3.invoke (A1); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }    }classa{ Public voidprint () {System.out.println ("Hello World"); }         Public voidPrintintAintb) {System.out.println (a+b); }     Public voidprint (String a,string b) {System.out.println (A.touppercase ()+b.tolowercase ()); }        }

2. Case, obtaining its property value through the property name of the standard JavaBean

Five. Generics

1. What is generics? Take a look at the following two statements

// only a number        of string types can be passed New Arraylist<string>();         New ArrayList ();

2. The nature of generics, see the demo below

 Public classfanxing {/*** Class,method to understand the nature of generics *@paramargs*/     Public Static voidMain (string[] args) {        //only a number of string types can be passedarraylist<string> list =NewArraylist<string>(); ArrayList List2=NewArrayList (); List.add ("Hello"); //List.add (a);Class C1 =List.getclass (); Class C2=List2.getclass (); SYSTEM.OUT.PRINTLN (C1==C2); }}

The following conclusions can be drawn from the running results:

Reflected operations are post-compilation operations

C1==C2 results return True to indicate that generics are de-generalized after compilation

Generics in Java are protected from erroneous input and are only valid during the compilation phase

3. Use the reflection of the method to operate, bypassing the compilation

Try{Method A1=c1.getmethod ("Add", Object.class); Object A2= A1.invoke (list, 2);System.out.println (List.size ());        SYSTEM.OUT.PRINTLN (list); } Catch(SecurityException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(nosuchmethodexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }Catch(IllegalArgumentException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(illegalaccessexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(InvocationTargetException e) {//TODO auto-generated Catch blockE.printstacktrace (); }

The running result of the code validates the generics and concludes that bypassing the compilation operation bypasses the generics

Finally, thank you for reading.

A gradual understanding of java--reflection

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.