Home  >  Article  >  Java  >  Introduction to analysis of Java reflection

Introduction to analysis of Java reflection

高洛峰
高洛峰Original
2017-03-09 19:05:40978browse

This document describes the analysis and introduction of Java reflection

1. What is reflection?
From Baidu Encyclopedia, we can know that Java reflection is in the running state. For any class, we can know all the properties and methods of this class; for any object, we can call any of its methods and properties; and can change its properties. And this is why Java is considered dynamic (or quasi-dynamic, why is it said to be quasi-dynamic, because the general definition of a dynamic language is that when the program is running, it allows the program structure or variable type to be changed. This language is called a dynamic language. From this point of view, Perl, Python, and Ruby are dynamic languages, and C++, Java, and C# are not dynamic languages.) A key property of languages.

2. What can reflection do?
We know that the reflection mechanism allows the program to obtain the internal information of any class with a known name at runtime, including its modifiers (modifiers), fields (properties), methods (methods), etc., and can be changed at runtime. fields content or calling methods. Then we can write code more flexibly, and the code can be assembled at runtime without the need for source code linking between components, reducing the coupling of the code; there is also the implementation of dynamic agents, etc.; but we need to pay attention to the improper use of reflection. It will be very costly!

3. The specific implementation of reflection

The following is a basic class Person

package com.ys.reflex;
public class Person {
    //私有属性
    private String name = "Tom";
    //公有属性
    public int age = 18;
    //构造方法
    public Person() {    
    }
    //私有方法
    private void say(){
        System.out.println("private say()...");
    }
    //公有方法
    public void work(){
        System.out.println("public work()...");
    }
}

①. Get the Class 3 This way

//1、通过对象调用 getClass() 方法来获取,通常应用在:比如你传过来一个 Object
//  类型的对象,而我不知道你具体是什么类,用这种方法
  Person p1 = new Person();
  Class c1 = p1.getClass();
        
//2、直接通过 类名.class 的方式得到,该方法最为安全可靠,程序性能更高
//  这说明任何一个类都有一个隐含的静态成员变量 class
  Class c2 = Person.class;
        
//3、通过 Class 对象的 forName() 静态方法来获取,用的最多,
//   但可能抛出 ClassNotFoundException 异常
  Class c3 = Class.forName("com.ys.reflex.Person");

It should be noted that:A class will only have one Class instance in the JVM,That is, we will perform the above-obtained c1, c2, c3 equals comparison, found to be true

②,Get member variables, member methods, interfaces, super classes, constructors, etc. through the Class class

Check the API and you can see that Class has many methods:

GetName(): Get the complete name of the class.
GetFields(): Get the public type attributes of the class.
 getDeclaredFields(): Get all attributes of the class. Including private declared and inherited classes
GetMethods(): Get the public type method of the class.
 getDeclaredMethods(): Get all methods of the class. Including private declared and inherited classes
GetMethod(String name, Class[] parameterTypes): Get the specific method of the class, the name parameter specifies the name of the method, and the parameterTypes parameter specifies the parameter type of the method.
GetConstructors(): Get the public type constructor of the class.
 getConstructor(Class[] parameterTypes): Get the specific constructor method of the class. The parameterTypes parameter specifies the parameter type of the constructor method.
 newInstance(): Create an object of this class through the constructor method of the class without parameters.

We use an example to comprehensively demonstrate the above method:

//获得类完整的名字
String className = c2.getName();
System.out.println(className);//输出com.ys.reflex.Person
        
//获得类的public类型的属性。
Field[] fields = c2.getFields();
for(Field field : fields){
   System.out.println(field.getName());//age
}
        
//获得类的所有属性。包括私有的和继承类的
Field [] allFields = c2.getDeclaredFields();
for(Field field : allFields){
    System.out.println(field.getName());//name    age
}
        
//获得类的public类型的方法。这里包括 Object 类的一些方法
Method [] methods = c2.getMethods();
for(Method method : methods){
    System.out.println(method.getName());//work waid equls toString hashCode等
}
        
//获得类的所有方法。
Method [] allMethods = c2.getDeclaredMethods();
for(Method method : allMethods){
    System.out.println(method.getName());//work say
}
        
//获得指定的属性
Field f1 = c2.getField("age");
System.out.println(f1);
//获得指定的私有属性
Field f2 = c2.getDeclaredField("name");
//启用和禁用访问安全检查的开关,值为 true,则表示反射的对象在使用时应该取消 java 语言的访问检查;反之不取消
f2.setAccessible(true);
System.out.println(f2);
                
//创建这个类的一个对象
Object p2 =  c2.newInstance();
//将 p2 对象的  f2 属性赋值为 Bob,f2 属性即为 私有属性 name
f2.set(p2,"Bob");
//使用反射机制可以打破封装性,导致了java对象的属性不安全。 
System.out.println(f2.get(p2)); //Bob
        
//获取构造方法
Constructor [] constructors = c2.getConstructors();
for(Constructor constructor : constructors){
    System.out.println(constructor.toString());//public com.ys.reflex.Person()
}

4. Reflection summary

Flexible use of reflection can make our code more flexible, here is an example of JDBC native code registration Drivers, hibernate's entity classes, Spring's AOP, etc. all have reflection implementations. But everything has two sides. Reflection will also increase the performance and complexity of the system. Reasonable use is the truth!

The above is the detailed content of Introduction to analysis of Java reflection. 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