Java reflection technology

Source: Internet
Author: User

Java reflection mechanism: we all know that a java class contains member variables, member methods, and constructor methods. The reflection mechanism is to dynamically obtain information in these classes, and dynamically call the object method. Generally, java reflection APIs are used only when the framework is designed. However, you need to understand the basic principles and methods of the java reflection mechanism, it can help us to learn and apply frameworks in the future. Understanding the Class: the Class represents the bytecode of A Class. To use reflection, you need to obtain the corresponding Class object and then use this object, you can dissect the member variables and member methods of the class. Common Methods of Class: getConstructor () Get constructor getMethod () Get member method getField () Get member variable getDeclaredConstructor () Get private constructor getDeclaredMethod () getDeclaredField () method for obtaining private member variables how to obtain Class Object: [java] // use the forName () method of Class, this method is the most commonly used Class class1 = Class. forName ("com. java4fun. reflect. person "); // use Person. class Class class2 = Person. class; // obtain Class class3 = new Person () through an object (). getClass (); the use of reflection, simply put, is through the Class Object of the Class, Obtain the corresponding Field, Method, and Constructor objects and perform related operations. Next we will use reflection to dissect the Person class and give the Person class: [java] public class Person {public String name = "java"; private int age = 2013; // No parameter constructor public Person () {} public Person (int age) {super (); this. age = age;} // private constructor private Person (String name) {super (); this. name = name;} public Person (String name, int age) {super (); this. name = name; this. age = age;} public int getAge () {return age;} public String getName () {Return name;} public void setAge (int age) {this. age = age;} public void setName (String name) {this. name = name;} public static void getMessage (String message) {System. out. println (message);} public static void getFriends (String friends []) {for (String s: friends) {System. out. print (s + "\ t") ;}@ Override public String toString () {return "Person [name =" + name + ", age = "+ age +"] ";} private Void secret (String secret) {System. out. println (secret);} public void run (int num) {System. out. println (num) ;}} get the constructor: [java] import java. lang. reflect. constructor; public class ConstructorTest {// use the reflection technology to complete the Person. class-related operations public static void main (String [] args) throws Exception {constructor1 (); // obtain and use constructor2 () for a constructor2 () without parameters (); // use constructor3 () for obtaining constructors with parameters; // for obtaining private constructors} // for obtaining private Constructors Static void constructor3 () throws Exception {// get the Person bytecode object. Class clazz = Class. forName ("com. java4fun. reflect. Person"); // gets the private constructor object. Constructor c = clazz. getDeclaredConstructor (String. class); // because the private constructor cannot directly construct objects, you need to call setAccessible (). // This method comes from the AccessibleObject class, it is the base class c of the Field, Method, and Constructor object. setAccessible (true); // use this constructor to construct a Person object Person p = (Person) c. newInstance ("private constructor"); System. out. println (p);} // access the private static void constructor2 () throws Exception {// obtain the bytecode object of Person. Class clazz = Class. forName ("com. java4fun. reflect. Person"); // obtain the constructor object with parameters. Constructor c = clazz. getConstructor (String. class, int. class); // use this constructor to construct a Person object Person p = (Person) c. newInstance ("hello", 110); System. out. println (p);} // access the private static void constructor1 () throws Exception {// obtain the bytecode object of Person. Class clazz = Class. forName ("com. java4fun. reflect. Person"); // gets a constructor object without parameters. Constructor c = clazz. getConstructor (null); // use this constructor to construct a Person object Person p = (Person) c. newInstance (null); System. out. println (p); // The Class also provides a method for directly constructing an object using a no-argument constructor. // Person person = (Person) clazz. newInstance (); // System. out. println (person) ;}} member method: [java] import java. lang. reflect. method; public class MethodTest {// use the reflection technology to complete the Person. public static void main (String [] args) throws Exc Eption {// method1 (); // obtain and use methods without parameters // method2 (); // obtain methods with parameters and use method3 (); // use method4 () to obtain the private member method; // The parameter is an array solution} // obtain the non-argument member method private static void method1 () throws Exception {// get the Person bytecode object. Class clazz = Class. forName ("com. java4fun. reflect. person "); // obtain the Method without parameters. The public String getName () {} Method m = clazz is reflected in the Person class. getMethod ("getName", null); // to run this method, an object is required for running the method. For convenience, you can directly create an object using the traditional method here. Person p = new Person ("HelloWorld", 23); String name = (String) m. invoke (p, null); System. out. println (name) ;}// obtain the parameter-based Member method private static void method2 () throws Exception {// obtain the Person bytecode object. Class clazz = Class. forName ("com. java4fun. reflect. person "); // obtain the Method with parameters, reflecting the public void run (int num) {} Method m = clazz in the Person class. getMethod ("run", int. class); // run this method. Because the operation of the method requires an object, you can directly create an object using the traditional method here for convenience. Person p = new Person ("HelloWorld", 23); m. invoke (p, 11111);} // obtain the private member method private static void method3 () throws Exception {// obtain the Person bytecode object. Class clazz = Class. forName ("com. java4fun. reflect. person "); // private Method, reflecting the private void secret (String secret) {} Method m = clazz in the Person class. getDeclaredMethod ("secret", String. class); // allow private methods to access m. setAccessible (true); // run this method. Because the operation of the method requires an object, you can create an object using the traditional method for convenience. Person p = new Person ("HelloWorld", 23); m. invoke (p, "gained recently");} // The parameter is an array solution private static void method4 () throws Exception {// get the byte code object of Person. Class clazz = Class. forName ("com. java4fun. reflect. person "); // obtain the static Method, reflecting the public static void getFriends (String friends []) {} Method m = clazz in the Person class. getMethod ("getFriends", String []. class); // an error occurs when calling the method. Due to issues left over by the version, the new String [] {"java", "c ", "c ++"} is considered as "java" "c" "c ++" // m. invoke (null, new String [] {"java", "c", "c ++"}); // equivalent to getFriends ("java", "c ", "c ++"); // call the method correctly, which is equivalent to passing the array into m as an object. invoke (null, (Object) ne W String [] {"java", "c", "c ++"}) ;}} member attributes: [java] import java. lang. reflect. field; public class FieldTest {// use the reflection technology to complete the Person. public static void main (String [] args) throws Exception {method1 (); // obtain the property method2 (); // obtain private attributes} // obtain the private static void method1 () throws Exception {// obtain the bytecode object of Person. Class clazz = Class. forName ("com. java4fun. reflect. person "); // get attributes, reflecting public String name =" java "in the Person class; Attribute Field f = clazz. getField ("name"); // you must specify an object to use the property. For convenience, you can create an object using the traditional method. Person p = new Person (); Class type = f. getType (); if (type. equals (String. class) {String name = (String) f. get (p); System. out. println (name) ;}}// obtain the private property private static void method2 () throws Exception {// obtain the Person bytecode object. Class clazz = Class. forName ("com. java4fun. reflect. person "); // get the private property, reflecting the private int age = 2013 in the Person class; Attribute Field f = clazz. getDeclaredField ("age"); f. setAccessible (true); // you must specify an object to use the property. For convenience, you can create an object using the traditional method. Person p = new Person (); Class type = f. getType (); if (type. equals (int. class) {int age = f. getInt (p); System. out. println (age );}}}

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.