Java reflection mechanism Learning (1)

Source: Internet
Author: User

[Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> String classPath = "com. test. hzw. bean. test_user "; // Class path of B cls = Class. forName (classPath); Field [] fieldlist = cls. getDeclaredFields (); for (int I = 0; I <fieldlist. length; I ++) {Field identifier = fieldlist [I]; System. out. println ("attributes of sister paper =" + attributes. getName (); System. out. println ("sister paper type name =" + paper. getType () ;}</SPAN> String classPath = "c Om. test. hzw. bean. test_user "; // Class path of B cls = Class. forName (classPath); Field [] fieldlist = cls. getDeclaredFields (); for (int I = 0; I <fieldlist. length; I ++) {Field identifier = fieldlist [I]; System. out. println ("attributes of sister paper =" + attributes. getName (); System. out. println ("sister paper type name =" + paper. getType ();} the reflection mechanism of Java, which can obtain the Class object corresponding to the path according to the Class path during java runtime. Obtain the member variables, methods, and structures of the class based on the class object, even if they are private. What are these things? You can use them to determine or call them to complete some functions. Class: the premise of a Class is to obtain the Class object. So you have to look at the java. lang. Class. Continue to Google a moment, found that a senior wrote an article: http://blog.csdn.net/hzw2312/article/details/8637199 article is very OK, I borrow here, it is not more description. Field: The Field class of the class member variable. It provides information about a single Field of the class or interface and its dynamic access permissions. You can use four static methods of Class to obtain the Field object and array: The first getField method returns a Field object, this object reflects the declared public fields (including inherited fields) specified for the Class object or interface ). The second method, getDeclaredField, returns a Field object that reflects the specified declared Field (excluding inherited fields) of the Class object or interface ). The name parameter is a String that specifies the abbreviation of the required field. [Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} try {// The getField method will not write Field ff = class1.getDeclaredField ("name"); System. out. println (ff. getName (); System. out. println (ff. getType ();} catch (SecurityException e) {E. printStackTrace ();} catch (NoSuchFieldException e) {e. printStackTrace () ;}</SPAN> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} try {// The getField method will not write Field ff = class1.getDeclaredField ("name"); System. out. println (ff. getName (); System. out. println (ff. getType ();} catc H (SecurityException e) {e. printStackTrace ();} catch (NoSuchFieldException e) {e. printStackTrace ();} the third method getFields returns all accessible public fields (including inherited fields) of the Class or interface represented by the Class object ). The fourth getDeclaredFields method returns an array of the Field object, which reflects all fields declared by the Class object or interface. Includes public, protected, default (Package) Access, and private fields, but does not include inherited fields. The elements in the returned array are not sorted or in any specific order. If this Class or interface does not declare any fields, or this Class object represents a basic type, an array Class, or void, this method returns an array with a length of 0. [Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Field [] f = class1.getDeclaredFields (); for (int I = 0; I <f. length; I ++) {Field field = f [I]; System. out. println ("attribute name:" + field. getName (); System. out. println ("genus Sex type: "+ field. getType () ;}</SPAN> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Field [] f = class1.getDeclaredFields (); for (int I = 0; I <f. length; I ++) {Field field = f [I]; System. out. println ("attribute name:" + field. getName (); System. out. println ("attribute type:" + field. getType ();} Method: The Method of the class provides information about a separate Method on the class or interface (and how to access the Method. The reflected methods may be class methods or instance methods (including abstract methods ). Like Field, Method objects and arrays are obtained through four static methods of Class: The first getMethod returns a Method object, it reflects the specified public member methods of the Class or interface represented by this Class object. The name parameter is a String used to specify the abbreviated name of the required method. The parameterTypes parameter is an array of Class objects that identify the method parameter type in declared order. If parameterTypes is null, it is processed by an empty array. The second getDeclaredMethod returns a Method object, which reflects the declared methods specified for the Class object or interface. The name parameter is a String that specifies the short name of the required method. The parameterTypes parameter is an array of Class objects. It identifies the type of the parameters of the method in declared order. If multiple methods with the same parameter type are declared in a class, and one of the methods has a special return type than other methods, this method is returned; otherwise, you can select a method. If the name is "<init>" or "<clinit>", a NoSuchMethodException is thrown. [Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Method m = null; try {m = class1.getDeclaredMethod ("getPass"); // enter the name of any Method in the class as the parameter} catch (SecurityException e) {e. printStackTrace ();} catch (NoSuchMethodExcepti On e) {e. printStackTrace ();} System. out. println ("method name:" + m. getName (); System. out. println ("method return type:" + m. getReturnType (); </SPAN> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Method m = null; try {m = class1.getDeclaredMethod ("getPass"); // enter the name of any Method in the class as the parameter} catch (SecurityEx Ception e) {e. printStackTrace ();} catch (NoSuchMethodException e) {e. printStackTrace ();} System. out. println ("method name:" + m. getName (); System. out. println ("method return type:" + m. getReturnType (); the third getMethods returns an array containing some Method objects, these objects reflect the public member methods of the classes or interfaces represented by this Class Object (including those declared by the Class or interface and those inherited from the superclass and superinterfaces. The array class returns all (public) member methods inherited from the Object class. The elements in the returned array are not sorted or in any specific order. If this Class object represents a Class or interface without public member methods, or a basic type or void, this method returns an array of 0 in length. The fourth getDeclaredMethods returns an array of Method objects, which reflect all methods declared by the Class object or interface, including public, protected, default (Package) Access, and private methods, but does not include the inherited methods. The elements in the returned array are not sorted or in any specific order. If this Class or interface does not declare any methods, or this Class object represents a basic type, an array Class, or void, this method returns an array with a length of 0. Class initialization method <clinit> is not included in the returned array. If the class declares multiple public member methods with the same parameter type, they are included in the returned array. [Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Method [] ms = class1.getDeclaredMethods (); for (int I = 0; I <ms. length; I ++) {Method m = MS [I]; System. out. println ("method name:" + m. getName (); System. out. println ("method return Return type: "+ m. getReturnType () ;}</SPAN> Class class1 = null; try {// com. test. hzw. bean. test_user is the full path name of the Class class1 = Class. forName ("com. test. hzw. bean. test_user ");} catch (ClassNotFoundException e) {e. printStackTrace ();} Method [] ms = class1.getDeclaredMethods (); for (int I = 0; I <ms. length; I ++) {Method m = MS [I]; System. out. println ("method name:" + m. getName (); System. out. println ("method return type:" + m. getReturnType ();} Con Structor: Class Construction provides information about a single constructor of the class and its access permissions. Construct the same Constructor object and array as the preceding two classes and obtain the Constructor object through four static methods of the Class: The first getConstructor returns a Constructor object, it reflects the specified public constructor of the Class represented by this Class object. The second getDeclaredConstructor returns a Constructor object, which reflects the specified Constructor of the Class object or interface. The third getConstructors returns an array containing some Constructor objects, which reflect all the common Constructor methods of the classes represented by this Class object. The fourth return an array of the getDeclaredConstructors object, which reflects all the constructor methods of the Class declaration represented by this Class object. [Java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px"> import java. io. IOException; import java. lang. reflect. constructor;/*** get information about the Constructor of the specified class * @ author Hu Han 3 */public class ConstructorTest {private int I; private double j; // default ConstructorTest () {}// the overloaded ConstructorTest (int I, double j) throws IOException {this. I = I; this. j = j;}/*** @ param args */public static void main (String [] args) throws Exception {// obtain the Class Object Class cls = Class of this Class. forName ("com. test. hzw. f. constructorTest "); // obtain all Constructor [] cs = cls declared in this class. getDeclaredConstructors (); // traverse for (Constructor c: cs) {// Constructor name System. out. println ("constructor name =" + c. getName (); // the class System in which the constructor declares. out. println ("the declared class =" + c. getDeclaringClass (); // Class [] ps = c. getParameterTypes (); // traversal parameter type for (int I = 0; I <ps. length; I ++) {System. out. println ("parameter type" + I + "=" + ps [I]);} // obtain the exception type set Class [] es = c. getExceptionTypes (); // traverses the exception type for (int I = 0; I <es. length; I ++) {System. out. println ("exception type" + I + "=" + es [I]);} // end a loop sign System. out. println ("-------------------------") ;}}</SPAN> import java. io. IOException; import java. lang. reflect. constructor;/*** get information about the Constructor of the specified class * @ author Hu Han 3 */public class ConstructorTest {private int I; private double j; // default ConstructorTest () {}// the overloaded ConstructorTest (int I, double j) throws IOException {this. I = I; this. j = j;}/*** @ param args */public static void main (String [] args) throws Exception {// obtain the Class Object Class cls = Class of this Class. forName ("com. test. hzw. f. constructorTest "); // obtain all Constructor [] cs = cls declared in this class. getDeclaredConstructors (); // traverse for (Constructor c: cs) {// Constructor name System. out. println ("constructor name =" + c. getName (); // the class System in which the constructor declares. out. println ("the declared class =" + c. getDeclaringClass (); // Class [] ps = c. getParameterTypes (); // traversal parameter type for (int I = 0; I <ps. length; I ++) {System. out. println ("parameter type" + I + "=" + ps [I]);} // obtain the exception type set Class [] es = c. getExceptionTypes (); // traverses the exception type for (int I = 0; I <es. length; I ++) {System. out. println ("exception type" + I + "=" + es [I]);} // end a loop sign System. out. println ("-------------------------") ;}} my com. test. hzw. bean. test_user class code [java] <SPAN style = "FONT-FAMILY: SimSun; FONT-SIZE: 14px ">/*** user class ** @ author Hu Han 3 **/public class test_user extends Test {private int id; // user id (auto-increment) private String name; // username private String pass; // password private int type; // type public String s = ""; public int getId () {return id ;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} private String getPass () {return pass;} public void setPass (String pass) {this. pass = pass;} public int getType () {return type;} public void setType (int type) {this. type = type ;}}</SPAN>

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.