Java (19)-reflection mechanism

Source: Internet
Author: User

I. Reflection:

The reflection mechanism means that the java program has the ability to view itself during runtime and can know all the attributes and methods in the class.

Reflection can be used to obtain any attributes and methods in the class. That is to say, reflection can break the encapsulation characteristics of the class and call private methods through reflection.

Let's look at a small example:

public class Test {    public static void main(String[] args) throws Exception {            Class
   classType  = MethodTest.class;        Method[]  method = classType.getDeclaredMethods();        for(Method m :method){        System.out.println(m);    }    }}


public class MethodTest extends MethodTest2 {        public MethodTest(){}   public void methodOne(){}private void methodTwo(){}private String methodThree(){          return null;}public int methodFour(){return 0;}}


Print:

Public void Reflection3.MethodTest. methodOne ()
Private void Reflection3.MethodTest. methodTwo ()
Private java. lang. String Reflection3.MethodTest. methodThree ()
Public int Reflection3.MethodTest. methodFour ()

This example shows all methods in the MethodTest class, including private methods and common methods. To use reflection, you must obtain the class Object of the class to be processed.


In addition to using MethodTest. class to obtain Class objects, there are two methods. In addition, I use three methods in total:

1). Use the static method forName: Class. forName ("java. lang. String") of the Class ");

Example:

Public>
All methods in String are printed.


2). Use the method in my first example. Class. class method.


3). Use the getClass () method of the object.


Example:

public class Test {    public static void main(String[] args) throws Exception {        String str = "abc";    Class
   classType  = str.getClass();        Method[]  method = classType.getDeclaredMethods();        for(Method m :method){        System.out.println(m);    }    }}

This will print all the methods in the String class.



How to use the public type method in the class through reflection:

Public class Test {public int sum (int a, int B) {return a + B;} public String Course (String str) {return "Course name:" + str ;} public static void main (String [] args) throws Exception {Class
 ClassType = Test. class; // The instance object of Test is returned through classType. newInstance () and can only be called without parameter construction. Object obj = classType. newInstance (); // The first parameter specifies the method name in the class, and the second parameter specifies the parameter type of the method. Why is there a second parameter, because there is an overloaded method in the class, use this to differentiate. Method sumMethod = classType. getMethod ("sum", int. class, int. class); Object sum = sumMethod. invoke (obj, 1, 2); System. out. println (Integer) sum); System. out. println ("========================================== ===== "); method courseMethod = classType. getMethod ("Course", String. class); Object course = courseMethod. invoke (obj, "Java"); System. out. println (course );}}


Print:

3
========================================================== =
Course name: Java


In the above example, we use classType. newInstance () to obtain the Test instance, but this method can only call the construction method without parameters. Use invoke when using the method (passing in an instance with a class and passing in a method parameter ).

The construction method with parameters uses the format: first obtain the Class object, then obtain the corresponding Constructor object through this object, and then generate it using the newInstance () method of this Constructor object.

If you want to generate an object through the Class Construction Method with parameters, you can only use the format in the following example.

Example:

Public class Test {public static void main (String [] args) throws Exception {Class
 ClassType = People. class;/** Constructor con = classType. getConstructor (new Class [] {}); * Object obj = con. newInstance (new Object [] {}); * You can also create objects without parameters. */Constructor con = classType. getConstructor (String. class); Object obj = con. newInstance ("zhangsan"); System. out. println (obj) ;}} class People {private String name; public People () {} public People (String name) {this. name = name ;}public String getName () {return name ;}}


How to use attributes and methods in the class through reflection:

Example:

Public class ReflectionTest {// execute the copy operation on an object. Public Object copy (Object o) throws Exception {Class
 Cs = Student. class; Object obj = cs. getConstructor (new Class [] {}). newInstance (new Object [] {}); Field [] field = cs. getDeclaredFields (); for (Field f: field) {String name = f. getName (); String firstLetter = name. substring (0, 1 ). toUpperCase (); // string used to obtain the set and get methods of the corresponding attribute. String getMethodName = "get" + firstLetter + name. substring (1); String setMethodName = "set" + firstLetter + name. substring (1); // obtain the set and get methods of the corresponding attribute. Method getMethod = cs. getMethod (getMethodName, new Class [] {}); Method setMethod = cs. getMethod (setMethodName, new Class [] {f. getType ()}); // obtain the returned value of the attribute. Object value = getMethod. invoke (o, new Object [] {}); // Add it to the Object to be returned. SetMethod. invoke (obj, new Object [] {value});} return obj;} public static void main (String [] args) throws Exception {Student t = new Student ("zhangsan", 1, 2); ReflectionTest r = new ReflectionTest (); Student s = (Student) r. copy (t); System. out. println (s. getAge () + "" + s. getName () + "" + s. getNumber () ;}} class Student {public String name; private int number; public int age; public Student () {} public Student (String name, int age, int number) {this. age = age; this. name = name; this. number = number;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int getNumber () {return number;} public void setNumber (int number) {this. number = number;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}}


Reflection is applied to Arrays:

Example:

Public class Test {public static void main (String [] args) throws Exception {Class
 ClassType = Class. forName ("java. lang. String"); // The first parameter sets the array type and the second parameter sets the array size. Object array = Array. newInstance (classType, 10); // The first parameter specifies the destination array, the second parameter specifies the storage location, and the third parameter specifies the elements to be saved. Array. set (array, 5, "java"); // print System. out. println (String) Array. get (array, 5 ));}}
Print: java

For multi-dimensional array creation:

Example:

Public class Test {public static void main (String [] args) throws Exception {// Integer. TYPE returns the native data TYPE, Integer. class returns the type of the class. The first parameter sets the type of the array and the second parameter sets the size of the array. Object array = Array. newInstance (Integer. TYPE, 3, 3); Object array2 = Array. get (array, 2); array2 = Array. get (array2, 2); Array. setInt (array2,); int [] [] [] a = (int [] []) array; // print System. out. println (a [2] [2] [2]) ;}}
Print: 10



Use reflection to call private methods in the class:

Example:

Public class PrivateTest {public static void main (String [] args) throws Exception {A a = new A (); Class
 ClassType =. getClass (); Method method = classType. getDeclaredMethod ("getHello", String. class); method. setAccessible (true); // suppress Java access permission String str = (String) method. invoke (a, "java"); System. out. println (str) ;}} class A {private String getHello (String str) {return "Hello! "+ Str ;}}
Print: Hello! Java



How to access private attributes:

Public class Reflection2 {public static void main (String [] args) throws Exception {Private2 p = new Private2 (); Class
 Cs = p. getClass (); Field f = cs. getDeclaredField ("name"); f. setAccessible (true); // suppress the Java peer question modifier check f. set (p, "lisi"); System. out. println (p. getName () ;}} class Private2 {private String name; public String getName () {return name ;}}

Print: lisi


Obtain the Class Object of the parent Class through subclass:


public class Test {  public static void main(String[] args) {     Class
  classType = Child.class;  System.out.println(classType);  classType = classType.getSuperclass();  System.out.println(classType);  classType = classType.getSuperclass();  System.out.println(classType);  }}class Child extends Parent{}class Parent{}

Print:

Class Reflection1.Child
Class Reflection1.Parent
Class java. lang. Object





Zookeeper

Zookeeper

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.