Summary and actual operation of the Java reflection mechanism

Source: Internet
Author: User

First, what is reflection 1, compile and run

Before you know what a Java reflection mechanism is, let's talk about the compilation and operation of Java.

Remember the first time you used Notepad to write the first Java program in a scene? From the command window, compile a. java file using the Javac command, generate a. class file, and then run the. class file using the Java command.

At compile time, the JVM checks the. java file for classes, the properties and methods of the class, the object of the class, and so on, if the corresponding information can be found, the compilation passes, otherwise it will compile an error or throw exception information.

At run time, the code logic is handled based on the. class file information, and exception information is thrown if a program run error is encountered.

Below we use a small example to illustrate the compilation and operation. Create a new animal class that creates different objects and executes different methods depending on the parameters passed in.

public class Animal{    public static void main(String[] args) {        if("Cat".equals(args[0])){            Cat cat = new Cat();            cat.eat();        }        if("Dog".equals(args[0])){            Dog dog = new Dog();            dog.eat();        }       }}

When compiling with the cmd command, an error occurs and no cat classes or dog classes are found.

E:\Java项目实战>javac Animal.javaAnimal.java:6: 错误: 找不到符号                        Cat cat = new Cat();                        ^  符号:   类 Cat  位置: 类 AnimalAnimal.java:6: 错误: 找不到符号                        Cat cat = new Cat();                                      ^  符号:   类 Cat  位置: 类 AnimalAnimal.java:11: 错误: 找不到符号                        Dog dog = new Dog();                        ^  符号:   类 Dog  位置: 类 AnimalAnimal.java:11: 错误: 找不到符号                        Dog dog = new Dog();                                      ^  符号:   类 Dog  位置: 类 Animal4 个错误

We created a new cat class, compiled the Cat class, compiled the animal class again, reported two errors, and could not find the dog class.

Animal.java:11: 错误: 找不到符号                        Dog dog = new Dog();                        ^  符号:   类 Dog  位置: 类 AnimalAnimal.java:11: 错误: 找不到符号                        Dog dog = new Dog();                                      ^  符号:   类 Dog  位置: 类 Animal

What if we want to use a cat class, regardless of whether the dog is present or not? That's the way to execute cat classes dynamically at run time, bypassing the compile period. How to bypass the compilation period? This requires the use of a Java reflection mechanism.

2, the concept of reflection

reflection is the ability to know all the properties and methods of a class in a running state, and any one of its methods for any object. this dynamic access to information and the ability to dynamically invoke object methods are called the reflection mechanism of the Java language .

Continue to the question left above, how to tune to the Cat class eat method without creating a new Dog.java file?

First, we will dynamically load the class based on the parameters passed in, then create an instance object of the class, and finally execute the method of the class. Because you cannot determine whether the passed parameter is a cat or a dog, you need to define a superclass or interface that allows the cat class to inherit the superclass or implement the interface, overload or override the Eat () method, and when creating an instance of the class, use only the instance of creating the superclass or interface.

public class AnimalBetter {    public static void main(String[] args) {        try {            Class c1 = Class.forName(args[0]);            IAnimal animal = (IAnimal)c1.newInstance();            animal.eat();        } catch (Exception e) {            e.printStackTrace();        }    }}

Here we are using the interface

public interface IAnimal {    public void eat();  }

The realization of CAT class

public class Cat implements IAnimal {    public void eat() {        System.out.println("Cat is eatting");    }}
Second, the advantages and disadvantages of reflection

With reflection, you can effectively extend functionality with minimal code churn. Like the small example above, if one day we want to use the Tiger class to do eat action, we also need to change the code of the Animalbetter class? The answer is no, just need to create a new Tiger class, implement IAnimal interface, rewrite the Eat method, you can, the other existing code no need to make any changes.

With reflection, you can dynamically create class instances and methods that use classes, parse class files, access private properties or methods of a class, and give reflection implementations to things that need to be handled at run time.

Since reflection is so good, why not use it in a wide range of projects? In fact, reflection is also a disadvantage. Reflection includes a number of dynamic types that the JVM cannot optimize for, the actual operation is less efficient than non-reflective operations, and the use of reflection is minimized in those frequently executed code or for modules with higher performance requirements. Reflection is not available in environments where the program has security restrictions. Reflection can access private properties or methods that can break encapsulation and produce unexpected results.

Third, how to use reflection 1, the use of the process

First, you get the class object for the operation's classes, and then you get and view the methods and properties in that class through the methods in class, and finally use the reflection API to manipulate the information.

2. Gets the class object of the classes to manipulate

There are three ways to get class objects for classes

(1) The class name of the class is already known

Class c2 = Animal.class;

In fact, any class has an implied static member variable class, and any class is an instance object of class, which we call the class type of the class.

(2) Objects of this class have been known, obtained by means of the GetClass method

Animal animal = new Animal();Class c3 = animal.getClass();

Whether it is the C2 above or the C3 here, it is the class type of the animal class, and a class can only be an instance object or a class type of class.

(3) using the forname () static method in class

Class c4 = Class.forName("Animal"); //forName(String str)中参数为类的全路径(包名+类名)
3. Get the properties and methods of a class

We write it as a tool class, as follows:

/** * Gets the properties and methods of the class * @author Ogawa 94 * @date June 24, 2018 */public class Classutil {/** * Gets the member variable information for the class * @param obj to manipulate        Class */public static void Getclassfieldinfo (Object obj) {//Gets the class object of the classes to manipulate class C = Obj.getclass (); Gets the member variable information for the class//Field class is the class under the Java.lang.reflect package, encapsulating the operation on class member variables field[] fs = C.getfields (); Gets the information of all public member variables field[] FS2 = C.getdeclaredfields (); Gets the information of the member variable declared by the class itself//using the foreach Traversal member variable for (Field field:fs2) {///Get the class type of the member variable type Cl            The FieldType = Field.gettype ();            Gets the name of the class type String typeName = Fieldtype.getname ();            Gets the name of the member variable String fieldName = Field.getname ();        System.out.println (TypeName + "" + fieldName);        }}/** * Gets the method information for the class * @param obj class to manipulate */public static void Getclassmethodinfo (Object obj) {        Gets the class object of the classes to manipulate class C = Obj.getclass (); Gets the name of the class to manipulate System.ouT.println ("The name of the class is:" + c.getname ()); Gets the method information for the class//Methods class is the class under the Java.lang.reflect package, encapsulating the operation of the class method method[] ms = C.getmethods (); Get all the public functions, including method[from the parent class] MS2 = C.getdeclaredmethods (); Gets all of the methods declared by the class itself, unrestricted access//traversal method for (method Method:ms2) {///Get the method's return value type class type            ReturnType = Method.getreturntype ();            System.out.print (Returntype.getname () + "");            Gets the method name System.out.print (method.getname () + "(");            Get the parameter type, get the class type of the parameter list type class[] para = method.getparametertypes ();            for (Class Class1:para) {System.out.print (Class1.getname () + ",");        } System.out.println (")"); }}/** * Gets the constructor of the class * @param obj to manipulate the class */public static void Getclassconstructormethodinfo (Object        OBJ) {//Gets the class object of the classes to be manipulated class C = Obj.getclass (); Gets the construction method information for this class//constructor class is Java.lang.refleThe class under the CT package encapsulates the operation of the construction method of the class constructor[] cs = c.getconstructors (); Get all public constructors constructor[] CS2 = C.getdeclaredconstructors ();            Get all constructors for (Constructor constructor:cs2) {System.out.print (Constructor.getname () + "(");            Gets the argument list of the constructor, resulting in the class type of the argument list class[] paramtypes = Constructor.getparametertypes ();            for (Class class1:paramtypes) {System.out.print (Class1.getname () + ",");        } System.out.println (")"); }    }}

Write the test class as follows:

public class Test {    public static void main(String[] args) {        System.out.println("----- 成员变量信息 -----");        ClassUtil.getClassFieldInfo(new Integer(2));        System.out.println("----- 构造方法信息 -----");        ClassUtil.getClassConstructorMethodInfo(new Integer(2));        System.out.println("----- 方法信息 -----");        ClassUtil.getClassMethodInfo(new Integer(2));    }}

The test results are as follows, you can compare the test results with the integer class.

-----member Variable Information-----int min_valueint MAX_VALUEjava.lang.Class type[c digits[c digittens[c digitones[i sizetableint Valueint sizeint Byteslong Serialversionuid-----Construction Method Information-----java.lang.Integer (int,) Java.lang.Integer ( Java.lang.String,)-----method Information-----The name of the class is: Java.lang.Integerint numberofleadingzeros (int,) int Numberoftrailingzeros ( int,) int bitcount (int,) Boolean equals (Java.lang.Object,) java.lang.String toString (Int,int,) java.lang.String ToString () java.lang.String tostring (int,) int hashcode (int,) int hashcode () int min (int,int,) int max (int,int,) int rever Sebytes (int,) int compareTo (java.lang.Integer,) int compareTo (java.lang.Object,) byte Bytevalue () short shortvalue () int intvalue () long longvalue () float floatvalue () Double doublevalue () Java.lang.Integer valueOf (Java.lang.string,int, ) Java.lang.Integer valueOf (int,) Java.lang.Integer valueOf (java.lang.String,) java.lang.String tohexstring (int,) int Compare (Int,int,) Java.lang.Integer decode (java.lang.String,) void GetChars (int,inT,[C,) int reverse (int,) int stringsize (int,) int sum (int,int,) int parseint (java.lang.String,) int parseint ( Java.lang.string,int,) long tounsignedlong (int,) int compareunsigned (int,int,) int divideunsigned (int,int,) int Formatunsignedint (Int,int,[c,int,int,) Java.lang.Integer Getinteger (Java.lang.string,java.lang.integer,) Java.lang.Integer Getinteger (Java.lang.string,int,) Java.lang.Integer Getinteger (java.lang.String,) int Highestonebit (int,) int lowestonebit (int,) int parseunsignedint (java.lang.String,) int Parseunsignedint ( Java.lang.string,int,) int remainderunsigned (int,int,) int rotateleft (int,int,) int rotateright (int,int,) int Signum ( int,) java.lang.String tobinarystring (int,) java.lang.String tooctalstring (int,) java.lang.String tounsignedstring ( int,) java.lang.String tounsignedstring (Int,int,) java.lang.String toUnsignedString0 (Int,int,)
4. Use the reflection API to manipulate classes
public class Methoddemo {public static void main (string[] args) {//The first way of writing a try {//Get C for the class to be manipulated Lass object Class c = Class.forName ("Sessionone.            Foo ");            Gets the Print method, M = C.getmethod ("print", string.class);            In the second way, new class[]{} can take multiple parameters, or it can be an empty Method m2 = C.getmethod ("Print", New Class[]{string.class});            The third way to get the class itself is to declare the method m3 = C.getdeclaredmethod ("print", string.class);        Execution Method M3.invoke (C.newinstance (), "Ogawa 94");        } catch (Exception e) {e.printstacktrace ();        }//The second way foo foo = new Foo ();        Foo.print ("Ogawa 94"); The third Way, try {Class C2 = Class.forName ("Sessionone.            Foo ");            Foo foo2 = (foo) c2.newinstance ();        Foo2.print ("Ogawa 94");        } catch (Exception e) {e.printstacktrace ();            }//Fourth notation try {foo Foo3 = new Foo (); CLass C3 = Class.forName ("Sessionone.            Foo ");            method = C3.getdeclaredmethod ("print", string.class);        Method.invoke (Foo3, "Ogawa 94");        } catch (Exception e) {e.printstacktrace ();    }}}class foo{public void print (String name) {System.out.println ("Hello," + name); }}
Iv. Practical application of reflection 1. Using in JDBC
Class.forName("com.mysql.jdbc.Driver");Connection conn = DriverManager.getConnection(url, user, password);

When loading the drive, reflection is used, and reflection is used in the source code of the getconnection, and the entire JDBC is associated with the reflection.

2. Use in Set generics
ArrayList list = new ArrayList();ArrayList<String> list2 = new ArrayList<String>();System.out.println(list.equals(list2)); //true        Class c = list.getClass();System.out.println("list的类类型名称:"+c.getName());Class c2 = list2.getClass();System.out.println("list2的类类型名称:"+c2.getName());System.out.println(c == c2); //true        // c1==c2结果返回true,说明编译之后集合的泛型是去泛型化的// Java中集合的泛型,是防止错误输入的,只在编译阶段有效,绕过编译就无效了// list2.add(20); 这样写,是会编译报错try {    System.out.println("list2中有"+list2.size()+"个元素");    Method m = c2.getMethod("add", Object.class);    m.invoke(list2, 20);    System.out.println("list2中有"+list2.size()+"个元素");    System.out.println(list2.toString()); //[20],已经将类型是整型的数添加到list2中} catch (Exception e) {    

The generics in the collection are only intended to prevent compilation errors, and all of the generics are purged at run-time.

3. Use in servlet

In previous Servlet series articles, reflection was used to complete a servlet processing multiple requests, depending on the detailed description of the article.

4, in the framework of the use of

In the mainstream framework, there are reflection shadows, through the configuration, annotations to complete some of the static loading of the class method to use reflection to dynamically load the class, the specific will be explained to the framework in detail.

Summary and actual operation of the Java reflection mechanism

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.