Review the reflection mechanism in Java

Source: Internet
Author: User

The use of class classes

Any class is an instance object of class, and this instance object has three ways of expressing it.

/** *  *//** *  @author  jacky 2014 December 27  */class Foo {  Void print ()  {  system.out.println ("foo");  }}public class reflect {  public static void main (String[] args)  {  Foo foo1 =  New foo ();  //  Any class is an instance object of class, and there are three representations of this instance object   //  The first expression: actually tells us that each class has an implicit static member class  class c1 = foo.class;  //  Second expression: The object of the class is known to get   class c2 = foo1.getclass () through the GetClass method;  /**    *  everything is objects   classes are objects, instance objects of class classes    */  //  regardless of c1 or  C2 all represent the class type of the Foo class, and a class can only be an instance object of Class   system.out.println (C1 == C2);  //  The third expression: the object of this class is known to get   Class c3 = null;  try {    by the GetClass method Com.jacky.reflect--> Package Name    c3 = clasS.forname ("Com.jacky.reflect.Foo");  } catch  (classnotfoundexception e)  {    // todo auto-generated catch block   e.printstacktrace ();   }  system.out.println (C2 == C3);  //  We can create an instance object of the class from the class type of the class---> by C1  RO C2 OR C3 Create instance object for Foo   try {   Foo foo =  ( Foo)  c1.newinstance ();//  requires a parameterless construction method    foo.print ();  } catch  ( Instantiationexception e)  {   // todo auto-generated catch block    e.printstacktrace ();  } catch  (illegalaccessexception e)  {    // todo auto-generated catch block   e.printstacktrace ();   } }}

Output:

Truetruefoo


Dynamic Load Class

First say static loading:

The new creation object is a statically loaded class that needs to load all the possible classes at compile time

As follows: The Excel class is not implemented, and if static loading requires all classes to be implemented. I can use dynamic loading to solve this problem so that the program can still run.

Class Office {public static void main (string[] args) {//new creates an object is a static load class that needs to load all possible classes at compile time//by dynamically adding            Download can resolve the problem if ("word". Equals (Args[0])) {Word w = new word ();        W.start ();            } if ("Excel". Equals (Args[0])) {Excel e = new Excel ();        E.start (); }    }}

Dynamic loading:

Class officebetter{    public static void main (String[] args)      {        try         {            //dynamic load class, at run time             class c = class.forname (Args[0]);             //create the class object through the class type              OfficeAble oa =  (officeable) C.newinstance ();             oa.start ();         }        catch  ( Exception e)         {             e.printstacKtrace ();        }             }}

Parameter Args[0] Specifies the class to load at run time. If we just implemented Excel, and for the implementation of the word class, we can specify that loading Excel

As follows:

Officeable.java:

Class Word implements officeable{public void Start () {System.out.println ("Word start"); }}

Interface officeable

Interface officeable{public void start ();

The Execute command argument is: Word

Results:

Word start
Get method information, construct etc.

Classutil.printclassmessage (Object obj)
Basic data type, void keyword exists class type

Classdemo2.java:

Public class classdemo2 { public static void main (String args[])   Class type of {   class c1 = int.class;//int     class c2 = Class type of  String.class;//String     Class c3 = double.class;    Class c4 = Double.class;   Class c5 = void.class;      system.out.println (C1.getname ());    system.out.println (C2.getName ());    system.out.println (C2.getsimplename ());    system.out.println (C3.getName ());    system.out.println (C4.getname ());    system.out.println (C5.getName ());     String hello =  "Xixi";  int i = 1;   Classutil.printclassmethodmessage (i);   classutil.printclassconmessage ("Hello");   Classutil.printclassconmessage (new iNteger (1));  }} 

Classutil.java:

public class classutil { /**  *  prints information about a class, including member functions of a class, member variables (get member functions only)   *    *  @author  jacky 2014 December 27   */ public static void  printclassmethodmessage (object obj)  {  //  to get information about a class, first get the class type of the class   class  c = obj.getclass (); //  is the object of which child class is passed, and C is the class type of the subclass   system.out.println ("Class name is:"  + c.getname ());   /**   * getmethods () gets all the public functions, including inherited by the parent class     * getdeclaredmethods () Gets all the methods of the class declaration, without asking for access rights &NBSP;&NBSP;&NBSP;*/&NBSP;&NBSP;METHOD[]&NBSP;MS  = c.getmethods ();  for  (int i = 0; i < ms.length;  i++)  {   //  gets the class type of the return value type of the method    Class returnType =  Ms[i].getreturntype ();    system.out.println ("Return value type:"  + returntype.getname ());    system.out.print (Ms[i].getname ()  +  "(");   //  get the parameter list, get the class type of the parameter list type    class[]  paramtypes = ms[i].getparametertypes ();   for  (Class class1 :  paramtypes)  {    system.out.print (Class1.getsimplename ()  +  ",");    }   system.out.println (")");  } } /**  *  Get member variables   *   *  @author  jacky 2014 December 27   */ public  static void printclassfieldmessage (object obj)  {  /**   * The  java.lang.reflect.field field class encapsulates the operation of a member variable    * getfields () The    * getdeclaredfields method gets the information for the member variable of all public () Gets the information of the member variable declared by the class itself    */  } /**  *  Print constructor Information   */ public static void  Printclassconmessage (object obj) &NBSP;{&NBSP;&NBSP;CLASS&NBSP;C&NThe Bsp;= obj.getclass ();  /**   *  constructor is also an object   Java.lang.Constructor encapsulates information about constructors    * getconstructors get constructors for all public      * getdeclaredconstructors () gets all the constructors    */  constructor[] cs =  c.getdeclaredconstructors ();  for  (CONSTRUCTOR&NBSP;CONSTRUCTOR&NBSP;:&NBSP;CS)  {    system.out.print (Constructor.getname ()  +  "(");   class  Paramtypes[] = constructor.getparametertypes ();   for  (Class class1 :  paramtypes)  {    system.out.print (Class1.getname ()  +  ",");    }   system.out.println (") \ n");   } }}
Method of Reflection Method.invoke (object, parameter list)
/** *  @author  jacky 2014 December 27  */public class classdemo { public  static void main (string args[])  {  //  get the Print (Int,int) method   a  a1 = new a ();   class c = a1.getclass ();  /**    *  get method, name and argument list determines  getmethod gets the method that the public method  getdeclaredmethod itself declares    */   try {   method m = c.getmethod ("Print", int.class,  Int.class) Reflection operation of the;   //  method    // a1.print (10,20)   method reflection using M-object for method invocation    //  If no return value is returned, NULL is returned, the return value type returns a specific return value of    m.invoke (A1,&NBSP;10,&NBSP;20);       method m1 = c.getmethod ("Print", new class[]{});    m1.invoke (a1, null);  } catch  (exception e)  {     todo autO-generated catch block   e.printstacktrace ();  } }}class a  { public void print () {  system.out.println ("Hello world"); }   Public void print (int a, int b)  {  system.out.println (a + b) ;  } public void print (string a, string b)  {   System.out.println (A.touppercase ()  + b.tolowercase ());  }}
The nature of generics

Reflected operations are post-compilation operations
The generics of the collection after compilation are de-generalized
Generics in Java are only prevented from being incorrectly entered and only valid during the compilation phase
Bypassing compilation is not working.

/** *  @author  jacky 2014 December 27  */public class classdemo { public  static void main (string args[])  {  List list = new  ArrayList ();  list<string> list1 = new arraylist<string> ();   list1.add ("Xixi");   class c1 = list.getclass ();   class c2 =  list1.getclass ();   system.out.println (C1&NBSP;==&NBSP;C2);  //true  // The actions that are reflected are compiled operations     /**   *  instructions after compilation The generics of the collection are de-generics    *  Generics in a collection in Java, just to prevent error input, only valid at compile time    *  bypass compilation Invalid    *  Validate: Method's reflection to operate, bypass compilation     */    try {   method m = c2.getmethod ("Add" ,  object.class);    m.invoke (list1,20);    system.out.println (List1);   } catch  (ExceptIon e)  {   // TODO Auto-generated catch block    E.printstacktrace ();   } }}

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