Home  >  Article  >  Java  >  In-depth understanding of reflection mechanism in Java

In-depth understanding of reflection mechanism in Java

黄舟
黄舟Original
2017-09-19 09:43:011146browse

This article mainly introduces relevant information for an in-depth understanding of the Java reflection mechanism. I hope that everyone can understand this part of the content through this article. Friends in need can refer to

In-depth understanding of the Java reflection mechanism

1. Concept 

Reflection is to map various components of Java into corresponding Java classes.

The construction method of the Class class is private and is created by the JVM.

Reflection is a feature of the Java language, which allows the program to perform self-examination and operate internal members during runtime (note that it is not compiled). For example, it allows a Java class to obtain all its member variables and methods and display them. This capability of Java may not be used much in practical applications, but this feature does not exist at all in other programming languages. For example, in Pascal, C, or C++ there is no way to obtain information about function definitions in a program. (From Sun)

JavaBean is one of the practical applications of reflection, which allows some tools to visually operate software components. These tools dynamically load and obtain the properties of Java components (classes) through reflection.

Reflection has been around since 1.2. The following three major frameworks will use the reflection mechanism. When it comes to the class "Class", you cannot directly new CLass(). Its object is a bytecode in the memory. . 

Instances of the Class class represent classes and interfaces in a running Java application. An enumeration is a class and an annotation is an interface. Each array belongs to a class that is mapped to a Class object, which is shared by all arrays with the same element type and dimension. The basic Java types (boolean, byte, char, short, int, long, float, and double) and the keyword void are also represented as Class objects. Class has no public constructor. Class objects are automatically constructed by the Java virtual machine when a class is loaded and by calling the defineClass method in the class loader.


 Person p1 = new Person();
 //下面的这三种方式都可以得到字节码
 CLass c1 = Date.class();
 p1.getClass(); 
 //若存在则加载,否则新建,往往使用第三种,类的名字在写源程序时不需要知道,到运行时再传递过来
 Class.forName("java.lang.String");

CLass.forName() bytecode has been loaded into the java virtual machine to get the bytecode; the bytecode class has not yet been generated in the java virtual machine The loader loads, and the loaded bytecode is buffered into the virtual machine.

Consider the following simple example and let's see how reflection works.


import java.lang.reflect.*; 

public class DumpMethods { 
  public static void main(String args[]) { 
   try { 
      Class c = Class.forName("java.util.Stack"); 

      Method m[] = c.getDeclaredMethods(); 

      for (int i = 0; i < m.length; i++) 
        System.out.println(m[i].toString()); 
   } 
   catch (Throwable e){ 
      System.err.println(e); 
   } 
  } 
}


 public synchronized java.lang.Object java.util.Stack.pop() 
 public java.lang.Object java.util.Stack.push(java.lang.Object) 
 public boolean java.util.Stack.empty() 
 public synchronized java.lang.Object java.util.Stack.peek() 
 public synchronized int java.util.Stack.search(java.lang.Object)

This lists the method names of the java.util.Stack class as well as their limiters and return types. This program uses Class.forName to load the specified class and then calls getDeclaredMethods to get the list of methods defined in the class. java.lang.reflect.Methods is a class used to describe a single method in a class.

The following example uses the Class object to display the class name of the object:


 void printClassName(Object obj) {
     System.out.println("The class of " + obj +
               " is " + obj.getClass().getName());
   }

You can also use a class literal (JLS Section 15.8.2) to obtain it A Class object of the specified type (or void). For example:


System.out.println("The name of class Foo is: "+Foo.class.getName());

When there is no object instance, there are two main methods.


//获得类类型的两种方式    
Class cls1 = Role.class;    
Class cls2 = Class.forName("yui.Role");

Note that in the second method, the parameter in forName must be the complete class name (package name + class name), and this method needs to catch exceptions. Now that you have cls1, you can create an instance of the Role class. Using the newInstance method of Class is equivalent to calling the default constructor of the class.


 Object o = cls1.newInstance(); 
 //创建一个实例    
//Object o1 = new Role();  //与上面的方法等价

2. Commonly used methods

1.isPrimitive (determine whether it is a basic type of bytecode)


public class TestReflect {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    String str = "abc";
    Class cls1 = str.getClass();
    Class cls2 = String.class;
    Class cls3 = null;//必须要加上null
    try {
      cls3 = Class.forName("java.lang.String");
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    System.out.println(cls1==cls2);
    System.out.println(cls1==cls3);

    System.out.println(cls1.isPrimitive());
    System.out.println(int.class.isPrimitive());//判定指定的 Class 对象是否表示一个基本类型。
    System.out.println(int.class == Integer.class);
    System.out.println(int.class == Integer.TYPE);
    System.out.println(int[].class.isPrimitive());
    System.out.println(int[].class.isArray());
  }
}
/*
 * true
true
false
true
false
true
false
true

 */
*/

2.getConstructor and getConstructors()

There is no order of construction methods in Java, and they are distinguished by type and number of parameters.


/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException {
    // TODO Auto-generated method stub
    String str = "abc";

    System.out.println(String.class.getConstructor(StringBuffer.class));
  }
}

3. The Filed class represents a member variable in a certain class.


import java.lang.reflect.Field;
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {
    ReflectPointer rp1 = new ReflectPointer(3,4);
    Field fieldx = rp1.getClass().getField("x");//必须是x或者y
    System.out.println(fieldx.get(rp1));

    /*
     * private的成员变量必须使用getDeclaredField,并setAccessible(true),否则看得到拿不到
     */
    Field fieldy = rp1.getClass().getDeclaredField("y");
    fieldy.setAccessible(true);//暴力反射
    System.out.println(fieldy.get(rp1));

  }
}

class ReflectPointer {

  public int x = 0;
  private int y = 0;

  public ReflectPointer(int x,int y) {//alt + shift +s相当于右键source
    super();
    // TODO Auto-generated constructor stub
    this.x = x;
    this.y = y;
  }
}

3. Typical examples

1. Change b in all String type member variables to a .


import java.lang.reflect.Field;
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {
    ReflectPointer rp1 = new ReflectPointer(3,4);
    changeBtoA(rp1);
    System.out.println(rp1);

  }

  private static void changeBtoA(Object obj) throws RuntimeException, Exception {
    Field[] fields = obj.getClass().getFields();

    for(Field field : fields) {
      //if(field.getType().equals(String.class))
      //由于字节码只有一份,用equals语义不准确
      if(field.getType()==String.class) {
        String oldValue = (String)field.get(obj);
        String newValue = oldValue.replace(&#39;b&#39;, &#39;a&#39;);
        field.set(obj,newValue);
      }
    }
  }
}

class ReflectPointer {

  private int x = 0;
  public int y = 0;
  public String str1 = "ball";
  public String str2 = "basketball";
  public String str3 = "itcat";

  public ReflectPointer(int x,int y) {//alt + shift +s相当于右键source
    super();
    // TODO Auto-generated constructor stub
    this.x = x;
    this.y = y;
  }

  @Override
  public String toString() {
    return "ReflectPointer [str1=" + str1 + ", str2=" + str2 + ", str3="
        + str3 + "]";
  }
}

2. Write a program to call the main method in the class based on the class name provided by the user.

Why use reflection?


import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
 * Java学习交流QQ群:589809992 我们一起学Java!
 */
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {
    String str = args[0];
    /*
     * 这样会数组角标越界,因为压根没有这个字符数组
     * 需要右键在run as-configurations-arguments里输入b.Inter(完整类名)
     * 
     */
    Method m = Class.forName(str).getMethod("main",String[].class);
    //下面这两种方式都可以,main方法需要一个参数

    m.invoke(null, new Object[]{new String[]{"111","222","333"}});
    m.invoke(null, (Object)new String[]{"111","222","333"});//这个可以说明,数组也是Object
    /*
     * m.invoke(null, new String[]{"111","222","333"})
     * 上面的不可以,因为java会自动拆包
     */
  }
}

class Inter {
  public static void main(String[] args) {
    for(Object obj : args) {
      System.out.println(obj);
    }
  }
}

3. Simulate the instanceof operator


class S { 
}  

public class IsInstance { 
  public static void main(String args[]) { 
   try { 
      Class cls = Class.forName("S"); 
      boolean b1 = cls.isInstance(new Integer(37)); 
      System.out.println(b1); 
      boolean b2 = cls.isInstance(new S()); 
      System.out.println(b2); 
   } 
   catch (Throwable e) { 
      System.err.println(e); 
   } 
  } 
}

In this example, a Class object of class S is created , and then checks whether some object is an instance of S. Integer(37) is not, but new S() is.

4. Method class

represents a method in a class (not an object).


import java.lang.reflect.Field;
import java.lang.reflect.Method;
/*
 * 人在黑板上画圆,涉及三个对象,画圆需要圆心和半径,但是是私有的,画圆的方法
 * 分配给人不合适。Java学习交流QQ群:589809992 我们一起学Java!
 * 
 * 司机踩刹车,司机只是给列车发出指令,刹车的动作还需要列车去完成。
 * 
 * 面试经常考面向对象的设计,比如人关门,人只是去推门。
 * 
 * 这就是专家模式:谁拥有数据,谁就是专家,方法就分配给谁
 */
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {
    String str = "shfsfs";
    //包开头是com表示是sun内部用的,java打头的才是用户的
    Method mtCharAt = String.class.getMethod("charAt", int.class);
    Object ch = mtCharAt.invoke(str,1);//若第一个参数是null,则肯定是静态方法
    System.out.println(ch);

    System.out.println(mtCharAt.invoke(str, new Object[]{2}));//1.4语法

  }

}

5. Array reflection

The Array tool class is used to complete the reflection operation of the array.

The same type and the same latitude have the same bytecode.

int.class and Integer.class are not the same bytecode, Integer.TYPE, TYPE represents the bytecode of the basic class corresponding to the packaging class int.class==Integer.TYPE


import java.util.Arrays;

/*
 * 从这个例子看出即便字节码相同但是对象也不一定相同,根本不是一回事
 * 
 */
public class TestReflect {
  public static void main(String[] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {
    int[] a = new int[3];
    int[] b = new int[]{4,5,5};//直接赋值后不可以指定长度,否则CE
    int[][] c = new int[3][2];
    String[] d = new String[]{"jjj","kkkk"};
    System.out.println(a==b);//false
    System.out.println(a.getClass()==b.getClass());//true
    //System.out.println(a.getClass()==d.getClass());  //比较字节码a和cd也没法比
    System.out.println(a.getClass());//输出class [I
    System.out.println(a.getClass().getName());//输出[I,中括号表示数组,I表示整数

    System.out.println(a.getClass().getSuperclass());//输出class java.lang.Object
    System.out.println(d.getClass().getSuperclass());//输出class java.lang.Object

    //由于父类都是Object,下面都是可以的
    Object obj1 = a;//不可是Object[]
    Object obj2 = b;
    Object[] obj3 = c;//基本类型的一位数组只可以当做Object,非得还可以当做Object[]
    Object obj4 = d;

    //注意asList处理int[]和String[]的区别
    System.out.println(Arrays.asList(b));//1.4没有可变参数,使用的是数组,[[I@1bc4459]
    System.out.println(Arrays.asList(d));//[jjj, kkkk]

  }
}

6. Conclusion 

The above is a simple use of the reflection mechanism. Obviously friends who have studied spring must understand why we can obtain specified methods and variables through configuration files. When we create objects, we pass in string The implementation is just like what you need, we will produce it for you, and we have been using Object, which shows that the dynamic characteristics of the Java language and the dependence are greatly reduced.

The above is the detailed content of In-depth understanding of reflection mechanism in Java. 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