Reflection mechanisms are provided in Java and C #. Using such reflection mechanisms can do a lot of useful things, such as Implementing AOP and other functions, I recently read a blog about implementing the internal mechanism of AOP, so I started to read some reflection articles. Here I will take out some of the code I wrote for you to share, soon, the C # code will be provided to get class information using the reflection mechanism.
Run the following command: (I put my Java program under C:/Java)
The running interface is as follows:
The detailed code is as follows:
Import java. Lang. Reflect .*;
Import java. util. RegEx .*;
Public class classinfo
{
Static void printinfor (class CC)
{
System. Out. println ("class name->" + CC. getname ());
}
Private Static pattern P = pattern. Compile ("/W + /.");
Public static void main (string ARGs [])
{
System. out. println ("************************************* ***********");
System. out. println ************** ");
System. Out. println ("Usage: Java classinfo Class Name (full name of the class )");
System. Out. println ("Example: Java classinfo string ");
System. Out. println ("currently supports short-form classes ");
System. out. println ("************************************* ***********");
If (ARGs. Length <1)
{
System. Out. println ("usage error ");
System. Out. println ("Example: Java classinfo string ");
System. Exit (0 );
}
Class C = NULL;
Try
{
C = Class. forname ("Java. Lang." + ARGs [0]);
Method [] M = C. getmethods ();
Constructor [] ctor = C. getconstructors ();
If (ARGs. Length = 1)
{
Printinfor (C );
Class [] interarray = C. getinterfaces ();
For (INT I = 0; I <interarray. length; I ++)
System. Out. println (C. getname () + "" + (I + 1) + "" + "interarray [I]. getname ());
Class Cy = C;
Int temp = 1;
Do
{
Cy = Cy. getsuperclass ();
System. Out. Print ("the" + temp + "level parent class ");
Printinfor (CY );
Temp ++;
}
While (Cy. getname ()! = "Java. Lang. Object ");
For (INT I = 0; I <M. length; I ++)
System. out. println ("nth" + (I + 1) + "method" + P. matcher (M [I]. tostring ()). replaceall (""));
For (INT I = 0; I <ctor. length; I ++)
System. out. println ("nth" + (I + 1) + "constructor" + P. matcher (ctor [I]. tostring ()). replaceall (""));
}
Else
{
System. Out. println ("this method can only contain one parameter ");
}
}
Catch (classnotfoundexception E)
{
System. Out. println ("the specified class information is not found ");
System. Exit (0 );
}
}
}
Note that
C = Class. forname ("Java. Lang." + ARGs [0]);
Method [] M = C. getmethods ();
Constructor [] ctor = C. getconstructors ();
This is the core of reflection code.
The core of understanding reflection code is that when Java is running, metadata about classes is stored in a special class. This class is called "class" in Java. Note, the C of the class here is capitalized, which is different from the ordinary class.