Select blog from lxblg
The reflection technology of Java is very powerful. sort out some documents !!
(If You Need To reprint it, please indicate the source !)
Lesson: Detection class examing class
1. Retrieving class objects
Obtain a Class Object (metadata)
A. Get it from the instance of the object.
Class C = mystery. getclass (); // (return class)
B. obtain from the subclass instance
Textfield T = new textfield ();
Class C = T. getclass ();
Class S = C. getsuperclass ();
C. If you know the class name, you can add. class to the name to obtain it.
Class C = java. AWT. Button. Class;
D. If the class name is unknown during compilation, you can use the class. forname () method to obtain it.
Class C = Class. forname (classstring );
2. Getting the class name
Get class name
C. getname ();
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class samplename {
Public static void main (string [] ARGs ){
Button B = new button ();
Printname (B );
}
Static void printname (Object O ){
Class C = O. getclass ();
String S = C. getname ();
System. Out. println (s );
}
}
3. Discovering Class Modifiers
Retrieve Modifier
A. Use the getmodifiers () method to obtain an integer id value.
B. Judge this value through the ispublic, isabstract, and isfinal methods of the Java. Reflect. modifier object.
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class samplemodifier {
Public static void main (string [] ARGs ){
String S = new string ();
Printmodifiers (s );
}
Public static void printmodifiers (Object O ){
Class C = O. getclass ();
Int M = C. getmodifiers ();
If (modifier. ispublic (m ))
System. Out. println ("public ");
If (modifier. isabstract (m ))
System. Out. println ("abstract ");
If (modifier. isfinal (m ))
System. Out. println ("final ");
}
}
4. Finding superclasses
Retrieve parent class
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class samplesuper {
Public static void main (string [] ARGs ){
Button B = new button ();
Printsuperclasses (B );
}
Static void printsuperclasses (Object O ){
Class subclass = O. getclass ();
Class superclass = subclass. getsuperclass ();
While (superclass! = NULL ){
String classname = superclass. getname ();
System. Out. println (classname );
Subclass = superclass;
Superclass = subclass. getsuperclass ();
}
}
}
5. Identifying the interfaces implemented by a Class
Retrieve the interface implemented by the specified class
For example:
Import java. Lang. Reflect .*;
Import java. Io .*;
Class sampleinterface {
Public static void main (string [] ARGs ){
Try {
Randomaccessfile r = new randomaccessfile ("myfile", "R ");
Printinterfacenames (R );
} Catch (ioexception e ){
System. Out. println (E );
}
}
Static void printinterfacenames (Object O ){
Class C = O. getclass ();
Class [] theinterfaces = C. getinterfaces ();
For (INT I = 0; I <theinterfaces. length; I ++ ){
String interfacename = theinterfaces [I]. getname ();
System. Out. println (interfacename );
}
}
}
6. Examining Interfaces
Determines whether a class is an interface.
Import java. Lang. Reflect .*;
Import java. util .*;
Class samplecheckinterface {
Public static void main (string [] ARGs ){
Class thread = thread. Class;
Class runnable = runnable. Class;
Verifyinterface (thread );
Verifyinterface (runnable );
}
Static void verifyinterface (Class C ){
String name = C. getname ();
If (C. isinterface ()){
System. Out. println (name + "is an interface .");
} Else {
System. Out. println (name + "is a class .");
}
}
}
Example: C. isinterface ()
7. Identifying class Fields
Finds all the domain members of the specified class.
Each data member can use Java. Reflect. Field to close the set of names, types, and modifiers.
You can also obtain or set the value of this Member through the corresponding method.
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class samplefield {
Public static void main (string [] ARGs ){
Gridbagconstraints G = new gridbagconstraints ();
Printfieldnames (g );
}
Static void printfieldnames (Object O ){
Class C = O. getclass ();
Field [] publicfields = C. getfields ();
For (INT I = 0; I <publicfields. length; I ++ ){
String fieldname = publicfields [I]. getname ();
Class typeclass = publicfields [I]. GetType ();
String fieldtype = typeclass. getname ();
System. Out. println ("name:" + fieldname +
", Type:" + fieldtype );
}
}
}
8. Discovering Class Constructors
Returns the constructor of a specified class.
When creating an instance of a class, it is done through the check method, which can be overloaded.
Each constructor can be used to describe each constructor, including the name, modifier, parameter type (class []), and exception list.
You can use the getconstructors method of a class to obtain the constructor array of the class.
Routine:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class sampleconstructor {
Public static void main (string [] ARGs ){
Rectangle r = new rectangle ();
Showconstructors (R );
}
Static void showconstructors (Object O ){
Class C = O. getclass ();
Constructor [] theconstructors = C. getconstructors ();
For (INT I = 0; I <theconstructors. length; I ++ ){
System. Out. Print ("(");
Class [] parametertypes =
Theconstructors [I]. getparametertypes ();
For (int K = 0; k <parametertypes. length; k ++ ){
String parameterstring = parametertypes [K]. getname ();
System. Out. Print (parameterstring + "");
}
System. Out. println (")");
}
}
}
9. Obtaining method information
Search Method
You can find all the methods that belong to a class and use getmethods to include the method array to obtain the return type, modifier, method name, and parameter list of the method.
Steps:
A. Specify the Class Object of the class
B. getmethods () Get method [] Object
C. traverse the array object
Routine:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class samplemethod {
Public static void main (string [] ARGs ){
Polygon P = new polygon ();
Showmethods (P );
}
Static void showmethods (Object O ){
Class C = O. getclass ();
Method [] themethods = C. getmethods ();
For (INT I = 0; I <themethods. length; I ++ ){
String methodstring = themethods [I]. getname ();
System. Out. println ("name:" + methodstring );
String returnstring =
Themethods [I]. getreturntype (). getname ();
System. Out. println ("return type:" + returnstring );
Class [] parametertypes = themethods [I]. getparametertypes ();
System. Out. Print ("parameter types :");
For (int K = 0; k <parametertypes. length; k ++ ){
String parameterstring = parametertypes [K]. getname ();
System. Out. Print ("" + parameterstring );
}
System. Out. println ();
}
}
}
Lesson: 2 processing objects
1. Creating objects
Generally, the following method is used to create an object:
Rectangle r = new rectangle ();
However, if you are developing a development tools, you may not know the class of the object to be generated before running it.
So we need to create an object like the following:
String classname;
//... Load classname from the user interface
Object o = new (classname); // wrong!
But the above is incorrect.
The correct method is to use the Reflection Feature of the class:
1) Using no-argument Constructors
For example:
Class classdefinition = Class. forname (classname); // specifies the runtime instance of the class.
Object = classdefinition. newinstance (); // call the no-argument constructor to generate an instance of the specified class.
2) using constructors that have arguments
The following steps are required for this technology:
A. Create a Class Object
B. Create a constructor object. The getconstructor (class [] Params) method is a class array suitable for the constructor.
C. Call the newinstance method on the constructor object to generate an object. The parameter is an object array and is equipped with this constructor.
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class sampleinstance {
Public static void main (string [] ARGs ){
Rectangle rectangle;
Class rectangledefinition;
Class [] intargsclass = new class [] {Int. Class, Int. Class };
Integer Height = new INTEGER (12 );
Integer width = new INTEGER (34 );
Object [] intargs = new object [] {height, width };
Constructor intargsconstructor;
Try {
// 1.
Rectangledefinition = Class. forname ("Java. AWT. rectangle ");
// 2.
Intargsconstructor =
Rectangledefinition. getconstructor (intargsclass); // locate the specified constructor.
// 3.
Rectangle =
(Rectangle) Createobject (intargsconstructor, intargs); // constructor description object, object []
} Catch (classnotfoundexception e ){
System. Out. println (E );
} Catch (nosuchmethodexception e ){
System. Out. println (E );
}
}
Public static object Createobject (constructor,
Object [] arguments ){
System. Out. println ("constructor:" + constructor. tostring ());
Object object = NULL;
Try {
Object = constructor. newinstance (arguments );
System. Out. println ("Object:" + object. tostring ());
Return object;
} Catch (instantiationexception e ){
System. Out. println (E );
} Catch (illegalaccessexception e ){
System. Out. println (E );
} Catch (illegalargumentexception e ){
System. Out. println (E );
} Catch (invocationtargetexception e ){
System. Out. println (E );
}
Return object;
}
}
2. Getting Field Values
If you are writing a development tool such as a debugger, you must be able to obtain field values. This is a three-step process:
To create a development tool such as debugger, you must discover filed values. The following are three steps:
A. Create a Class Object
B. Create a Field object through getfield
C. Call the field. getxxx (object) method (XXX is int, float, etc. If it is an object, it will be omitted; object refers to the actual
Example ).
For example:
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class sampleget {
Public static void main (string [] ARGs ){
Rectangle r = new rectangle (100,325 );
Printheight (R );
}
Static void printheight (rectangle R ){
Field heightfield;
Integer heightvalue;
Class C = R. getclass ();
Try {
Heightfield = C. getfield ("height ");
Heightvalue = (integer) heightfield. Get (R );
System. Out. println ("height:" + heightvalue. tostring ());
} Catch (nosuchfieldexception e ){
System. Out. println (E );
} Catch (securityexception e ){
System. Out. println (E );
} Catch (illegalaccessexception e ){
System. Out. println (E );
}
}
}
3. Setting Field Values
A. Create a Class Object
B. Create a Field object through getfield
C. call field. set (object, withparam) method (XXX is int, float, etc. If it is an object, it is omitted; object refers to the instance, withparam refers to the field with this field.
Import java. Lang. Reflect .*;
Import java. AWT .*;
Class sampleset {
Public static void main (string [] ARGs ){
Rectangle r = new rectangle (100, 20 );
System. Out. println ("Original:" + R. tostring ());
Modifywidth (R, new INTEGER (300 ));
System. Out. println ("modified:" + R. tostring ());
}
Static void modifywidth (rectangle R, integer widthparam ){
Field widthfield;
Integer widthvalue;
Class C = R. getclass ();
Try {
Widthfield = C. getfield ("width ");
Widthfield. Set (R, widthparam );
} Catch (nosuchfieldexception e ){
System. Out. println (E );
} Catch (illegalaccessexception e ){
System. Out. println (E );
}
}
}
4. Call the specified Method
A. Create a Class Object
B. Create a method object method, getmethod (string methodname, class []) Method
C. Call the method object, method. Invoke (object, object []). Two parameters: the first parameter refers to the object that calls the method, and the second parameter refers to the list of passed value objects.
The sample program that follows shows you how to invoke a method dynamically. The program retrieves the method object for the string. Concat method and then uses invoke to concatenate two string objects.
//
Import java. Lang. Reflect .*;
Class sampleinvoke {
Public static void main (string [] ARGs ){
String firstword = "hello"; // instance of the specified class
String secondword = "Everybody."; // variable
String bothwords = append (firstword, secondword );
System. Out. println (bothwords );
}
Public static string append (string firstword, string secondword ){
String result = NULL;
Class C = string. Class;
Class [] parametertypes = new class [] {string. Class };
Method concatmethod;
Object [] arguments = new object [] {secondword };
Try {
Concatmethod = C. getmethod ("Concat", parametertypes); // obtain the method object
Result = (string) concatmethod. Invoke (firstword, arguments); // call
} Catch (nosuchmethodexception e ){
System. Out. println (E );
} Catch (illegalaccessexception e ){
System. Out. println (E );
} Catch (invocationtargetexception e ){
System. Out. println (E );
}
Return result;
}
}