Home >Java >javaTutorial >Detailed explanation of example code of Java reflection mechanism

Detailed explanation of example code of Java reflection mechanism

黄舟
黄舟Original
2017-03-27 10:53:351176browse

This article mainly introduces the detailed explanation and examples of Java reflection mechanism. Friends who need it can refer to

Detailed explanation and examples of Java reflection mechanism

Reflection , I often heard them say that I had read some information and may have used it in Design Pattern, but I didn’t feel I had a deep understanding of it. I studied it again this time and it felt okay. Bar!

1, first look at the concept of reflection:

# mainly refers to the ability to access, detect and modify its own state or behavior. And can adjust or modify the status and related semantics of the behavior described by the application based on the status and results of its own behavior.

Reflection is a powerful tool in Java that allows us to easily create flexible code that can be assembled at runtime without source code linking between components. But improper use of reflection can be very costly!

If you are confused by the concept, continue reading.

2. The role of the reflection mechanism:

              1. Decompilation: .class-->.Java

                                                                                                                                                      through the reflection mechanism to access the properties , methods, construction methods , etc. of the java object ;

This seems easier to understand. Let’s look at how to implement these functions in detail.

#, let's take a look at SUN here with the class in those reflex mechanisms:

java.lang.Class;    
java.lang.reflect.Constructor; java.lang.reflect.Field;  
java.lang.reflect.Method;
java.lang.reflect.Modifier;

Many reflex methods, attributes and other operations, we can follow from Query among these four categories. Which sentence should we learn to constantly query API, that is our best teacher.

                                                                                                                                                                          ‐ ’ s ’ s 3 way to obtain the class, and let’s get the Employee type

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

            1. ,Create object: After getting the class, we create its object, using newInstance:

Class c =Class.forName("Employee"); 
 
//创建此Class 对象所表示的类的一个新实例 
Objecto = c.newInstance(); //调用了Employee的无参数构造方法.

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

a, first look at how to get all attributes:

//获取整个类 
   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);

b, get specific attributes, learn by comparing with traditional methods:

public static void main(String[] args) throws Exception{ 
    
<span style="white-space:pre"> </span>//以前的方式: 
 /* 
 User u = new User(); 
 u.age = 12; //set 
 System.out.println(u.age); //get 
 */ 
    
 //获取类 
 Class c = Class.forName("User"); 
 //获取id属性 
 Field idF = c.getDeclaredField("id"); 
 //实例化这个类赋给o 
 Object o = c.newInstance(); 
 //打破封装 
 idF.setAccessible(true); //使用反射机制可以打破封装性,导致了java对象的属性不安全。 
 //给o对象的id属性赋值"110" 
 idF.set(o, "110"); //set 
 //get 
 System.out.println(idF.get(o)); 
}

4, get method, and The construction method will not be described in detail, just look at the keywords:

##getDeclaredMethod("Method name", parameter type.class ,...)Get a specific method##Constructor keywordgetDeclaredConstructors()##getDeclaredConstructor(parameter type.class,… )
##Method keyword

Meaning

getDeclaredMethods()

Get all methods

getReturnType()

Get the return type of the method

getParameterTypes ()

Get the incoming parameter type of the method

Meaning

Get all constructors

Get a specific constructor

##Parent class and parent interface
Meaning

getSuperclass()
Get the parent class of a certain class

getInterfaces()
Get the interface implemented by a certain class

         这样我们就可以获得类的各种内容,进行了反编译。对于JAVA这种先编译再运行的语言来说,反射机制可以使代码更加灵活,更加容易实现面向对象。 

  五,反射加配置文件,使我们的程序更加灵活:

             在设计模式学习当中,学习抽象工厂的时候就用到了反射来更加方便的读取数据库链接字符串等,当时不是太理解,就照着抄了。看一下.NET中的反射+配置文件的使用:

             当时用的配置文件是app.config文件,内容是XML格式的,里边填写链接数据库的内容:

 <configuration> 
lt;appSettings> 
<add  key="" value=""/> 
lt;/appSettings> 
  </configuration>

 反射的写法:   

assembly.load("当前程序集的名称").CreateInstance("当前命名空间名称".要实例化的类名);

           这样的好处是很容易的方便我们变换数据库,例如我们将系统的数据库从SQL Server升级到Oracle,那么我们写两份D层,在配置文件的内容改一下,或者加条件选择一下即可,带来了很大的方便。            

         当然了,JAVA中其实也是一样,只不过这里的配置文件为.properties,称作属性文件。通过反射读取里边的内容。这样代码是固定的,但是配置文件的内容我们可以改,这样使我们的代码灵活了很多!

    综上为,JAVA反射的再次学习,灵活的运用它,能够使我们的代码更加灵活,但是它也有它的缺点,就是运用它会使我们的软件的性能降低,复杂度增加,所以还要我们慎重的使用它。

The above is the detailed content of Detailed explanation of example code of Java reflection mechanism. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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