Java reflection Summary

Source: Internet
Author: User

1 Java reflection is actually to find the complete information of a class through an instantiated object, for example, for the following form:
X = new x ();
X. getclass (). getname ();
The complete information of the class is output here, that is, "package name. Class Name ";
The three most common Class Object Instantiation Methods
Class <?> C1 = NULL; // specify the generic type
Class <?> C2 = NULL; // specify the generic type
Class <?> C3 = NULL; // specify the generic type
Try {
// The following operations are the most commonly used in development.
C1 = Class. forname ("org. lxh. demo15.getclassdemo. X ");
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
C2 = new x (). getclass (); // instantiate the object using the method in the object class
C3 = x. Class; // instantiate through class. Class
System. Out. println ("Class Name:" + c1.getname (); // obtain the class name.
System. Out. println ("Class Name:" + c2.getname (); // obtain the class name.
System. Out. println ("Class Name:" + c3.getname (); // obtain the class name.

2. Construct an instantiated object without Parameters
Suppose there is a class where a non-parameter constructor must exist, you can use the following method:
Class <?> C = NULL; // declare a Class Object
Try {
C = Class. forname ("org. lxh. demo15.instancedemo. person ");
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
Person per = NULL; // declare the person object
Try {
Per = (person) C. newinstance (); // instantiate the object
} Catch (exception e ){
E. printstacktrace ();
}
If a constructor with parameters exists in the class, implement it as follows:
Class <?> C = NULL; // declare a Class Object
Try {
C = Class. forname ("org. lxh. demo15.getclassdemo. person ");
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
Person per = NULL; // declare the person object
Constructor <?> Cons [] = NULL;
Cons = C. getconstructors ();
Try {
Per = (person) Cons [0]. newinstance ("Li Xinghua", 30); // instantiate the object
} Catch (exception e ){
E. printstacktrace ();
}
Getconsructors () in the class is used to obtain all the constructor methods in this class.

3. Obtain the class structure:
A gets all interfaces in the class:
Class <?> C [] = c1.getinterfaces (); // return all the Implemented interfaces in array form
For (INT I = 0; I <C. length; I ++ ){
System. Out. println ("implemented Interface Name:" + C [I]. getname (); // output interface Name
}
B. Obtain the parent class.
Class <?> C2 = c1.getsuperclass (); // obtain the parent class
C gets all the constructor methods and obtains them through the modifier class modifier.
Import java. Lang. Reflect. constructor; // import the constructor package
Import java. Lang. Reflect. modifier; // import the constructor package
Public class getconstructordemo03 {
Public static void main (string ARGs []) {
Class <?> C1 = NULL; // declare a Class Object
Try {
C1 = Class. forname ("org. lxh. demo15.person"); // instantiate an object
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
Constructor <?> CON [] = c1.getconstructors (); // obtain all the structures in a class
For (INT I = 0; I <con. length; I ++ ){
Class <?> P [] = CON [I]. getparametertypes (); // obtain all

Parameters
System. Out. Print ("constructor:"); // output structure, print directly
Int mo = CON [I]. getmodifiers (); // obtain the access permission
System. Out. Print (modifier. tostring (Mo) + ""); // get the Modifier
System. Out. Print (CON [I]. getname (); // obtain the constructor name.
System. Out. Print ("(");
For (Int J = 0; j <p. length; j ++ ){
System. Out. Print (P [J]. getname () + "Arg" + I );
If (j <p. Length-1 ){
// Determine whether this is the last parameter.
System. Out. Print (","); // output ","
}
}
System. Out. println ("){}");
}
}
}

D. obtain all the constructor methods of a class.
Public class getmethoddemo {
Public static void main (string ARGs []) {
Class <?> C1 = NULL; // declare a Class Object
Try {
C1 = Class. forname ("org. lxh. demo15.person"); // instantiate an object
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
Method M [] = c1.getmethods (); // obtain all methods
For (INT I = 0; I <M. length; I ++ ){
Class <?> R = m [I]. getreturntype (); // obtain the return value type.
Class <?> P [] = m [I]. getparametertypes (); // gets the type of all parameters
Int xx = m [I]. getmodifiers (); // get the Modifier
System. Out. Print (modifier. tostring (XX) + ""); // output Modifier
System. Out. Print (R + "");
System. Out. Print (M [I]. getname ());
System. Out. Print ("(");
For (Int J = 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 (); // retrieve an exception
If (ex. length> 0 ){
System. Out. Print (") throws ");
} Else {
System. Out. Print (")");
}
For (Int J = 0; j <ex. length; j ++ ){
System. Out. Print (ex [J]. getname ());
If (j <p. Length-1 ){
System. Out. Print (",");
}
}
System. Out. println ();
}
}
}

4. Call methods in the class through reflection
Class <?> C1 = NULL;
Try {
C1 = Class. forname ("org. lxh. demo15.person"); // instantiate a Class Object
} Catch (exception e ){}
Try {
Method met = c1.getmethod ("saychina"); // locate the saychina () method
Met. Invoke (c1.newinstance (); // CALL THE METHOD
} Catch (exception e ){
E. printstacktrace ();
}
}
If you want to call
Class <?> C1 = NULL;
Try {
C1 = Class. forname ("org. lxh. demo15.person"); // instantiate a Class Object
} Catch (exception e ){}
Try {
Method met = c1.getmethod ("sayhello", String. Class, Int. Class); // locate saychina

() Method
String Rv = NULL;
Rv = (string) met. Invoke (c1.newinstance (), "Li Xinghua", 30); // CALL THE METHOD
System. Out. println (RV );
} Catch (exception e ){
E. printstacktrace ();
}
}
5. Use reflection in combination with the factory Model
Package org. lxh. demo15.factorydemo02;
Import java. util. properties;
Import java. Io. file;
Import java. Io. fileoutputstream;
Import java. Io. fileinputstream;
Interface fruit {
Public void eat (); // fruit
}
Class Apple implements fruit {
Public void eat () {// override the Eat () method
System. Out. println ("** eat apple ");
}
};
Class orange implements fruit {
Public void eat (){
System. Out. println ("** eat oranges ");
}
};
Class init {
Public static properties getpro (){
Properties pro = new properties ();
File F = new file ("D: \ fruit. properties"); // locate the property File
Try {
If (F. exists () {// The file exists
Pro. Load (New fileinputstream (f); // read attributes
} Else {
Pro. setproperty ("apple", "org. lxh. demo15.factorydemo02. Apple ");
Pro. setproperty ("orange", "org. lxh. demo15.factorydemo02. Orange ");
Pro. Store (New fileoutputstream (F), "fruit class ");
}
} Catch (exception e ){}
Return pro;
}
};
Class factory {
Public static fruit getinstance (string classname ){
Fruit fruit = NULL;
Try {
Fruit = (fruit) class. forname (classname). newinstance ();
} Catch (exception e ){
E. printstacktrace ();
}
Return fruit;
}
};
Public class factorydemo02 {
Public static void main (string ARGs []) {
Properties pro = init. getpro ();
Fruit F = factory. getinstance (PRO. getproperty ("apple "));
If (F! = NULL ){
F. Eat ();
}
}
};

6. Dynamic Proxy:
Import Java. lang. reflect. invocationhandler;
Import Java. lang. reflect. proxy;
Import Java. lang. reflect. method;
interface subject {
Public String say (string name, int age ); // define the abstract method say
}< br> class realsubject implements subject {// implementation interface
Public String say (string name, int age) {
return "name:" + name + ", age:" + age;
}< BR> };
class myinvocationhandler implements invocationhandler {
private object OBJ;
Public object BIND (Object OBJ) {
This. OBJ = OBJ; // real topic class
return proxy. newproxyinstance (obj. getclass (). getclassloader (), obj. getclass

(). getinterfaces (), this);
}< br> Public object invoke (Object proxy, method, object [] ARGs) throws throwable {
Object temp = method. invoke (this. OBJ, argS); // call method
return temp;
}< BR> };
public class dynaproxydemo {
Public static void main (string ARGs []) {
subject sub = (subject) New myinvocationhandler (). BIND (New realsubject ();
string info = sub. say ("Li Xinghua", 30);
system. out. println (Info);
}< BR >};

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.