Home > Java > javaTutorial > body text

Reflection mechanism in JAVA

高洛峰
Release: 2016-12-12 11:40:47
Original
1264 people have browsed it

常 Reflex, I often listened to them at the time that I have seen some information, and may have been used in the design mode, but I feel that I do n’t have a deeper understanding of it. This time I re -learned it. It feels okay!


                                                                                                                                                                                                                                      but 1 but first a look at the concept of reflection:

                   The state of the described behavior and associated semantics.

                                                                                                                            Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled at runtime without the need for source code linking between components. But improper use of reflection can be very costly!晕 Look at the concept is very dizzy, continue to look down.

2. The role of the reflection mechanism:

1. Decompile: .class-->.java

2. Access the properties, methods, construction methods, etc. of java objects through the reflection mechanism;

It seems more like this It's easier to understand. Let's look at how to implement these functions in detail.

Third, let’s take a look at the classes that sun provides us with in the reflection mechanism:

java.lang.Class;

java.lang.reflect.Constructor; java.lang.reflect.Field;

java.lang.reflect.Method;

java.lang.reflect.Modifier;

We can query many methods, attributes and other operations in reflection from these four classes. Or should we learn to constantly query the API, that is our best teacher.

                                                                                                                                        ‐                                                                                                                               invited - requested,” in, to use.

//第一种方式:  
Classc1 = Class.forName("Employee");  
//第二种方式:  
//java中每个类型都有class 属性.  
Classc2 = Employee.class;  
   
//第三种方式:  
//java语言中任何一个java对象都有getClass 方法  
Employeee = new Employee();  
Classc3 = e.getClass(); //c3是运行时类 (e的运行时类是Employee)
Copy after login

3. Obtain attributes: divided into all attributes and specified attributes:

a. Let’s first look at how to get all attributes:

[java] view plain copy
 print?
Class c =Class.forName("Employee");  
  
//创建此Class 对象所表示的类的一个新实例  
Objecto = c.newInstance(); //调用了Employee的无参数构造方法.
Copy after login

b. Get specific attributes and learn by comparing with traditional methods:

//获取整个类  
            Class c = Class.forName("java.lang.Integer");  
              //获取所有的属性?  
            Field[] fs = c.getDeclaredFields();  
       
                   //定义可变长的字符串,用来存储属性  
            StringBuffer sb = new StringBuffer();  
            //通过追加的方法,将每个属性拼接到此字符串中  
            //最外边的public定义  
            sb.append(Modifier.toString(c.getModifiers()) + " class " + c.getSimpleName() +"{\n");  
            //里边的每一个属性  
            for(Field field:fs){  
                sb.append("\t");//空格  
                sb.append(Modifier.toString(field.getModifiers())+" ");//获得属性的修饰符,例如public,static等等  
                sb.append(field.getType().getSimpleName() + " ");//属性的类型的名字  
                sb.append(field.getName()+";\n");//属性的名字+回车  
            }  
      
            sb.append("}");  
      
            System.out.println(sb);
Copy after login

4. The acquisition method and construction method will not be described in detail. Just look at the keywords:

In this way, we can obtain various contents of the class and decompile them. For a language like JAVA that compiles first and then runs, the reflection mechanism can make the code more flexible and easier to implement object-oriented.加 射 射 射 射, reflects and configuration files, make our program more flexible:

In the design mode learning, we use reflection when learning abstract factories to read the database link string, etc. I didn’t quite understand it, so I just copied it. Take a look at the use of reflection+configuration files in .NET:

The configuration file used at the time was the app.config file, the content was xml format, and the content of the link database was filled in. The advantage is that it is very easy for us to change the database. For example, if we upgrade the system database from SQL Server to Oracle, then we write two D layers, change the content of the configuration file, or add conditions to select it, and it will bring A great convenience. J Of course, the same is true in Java, but the configuration file here is. PROPERTIES, called attribute files. Read the content inside through reflection. In this way, the code is fixed, but we can change the content of the configuration file, which makes our code much more flexible!

Reflection mechanism in JAVA

In summary, relearning JAVA reflection and using it flexibly can make our code more flexible, but it also has its shortcomings, that is, using it will reduce the performance and increase the complexity of our software, so we need to We use it carefully.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template