天天看點

java反射機制

在以前的文章中有簡單介紹過 java的反射機制 ,但沒有深入了解,補充一下。

反射:

反射是 JVM 在運作時才動态加載類或調用方法/通路屬性,它不需要事先(寫代碼的時候或編譯期)知道運作對象是誰。主要功能是在運作時判斷任意一個對象所屬的類;在運作時構造任意一個類的對象;在運作時判斷任意一個類所具有的成員變量和方法(通過反射甚至可以調用private方法);在運作時調用任意一個對象的方法

getName():獲得類的完整名字。
newInstance():通過類的不帶參數的構造方法建立這個類的一個對象
getSuperClass():這個類型的直接超類的全限定名 
isInterface():這個類型是類類型還是接口類型 
getTypeParamters():這個類型的通路修飾符 
getInterfaces():任何直接超接口的全限定名的有序清單 

得到構造器的方法
Constructor getConstructor(Class[] params) -- 獲得使用特殊的參數類型的公共構造函數,
Constructor[] getConstructors() -- 獲得類的所有公共構造函數
Constructor getDeclaredConstructor(Class[] params) -- 獲得使用特定參數類型的構造函數(與接入級别無關)
Constructor[] getDeclaredConstructors() -- 獲得類的所有構造函數(與接入級别無關)

獲得字段資訊的方法
Field getField(String name) -- 獲得命名的公共字段
Field[] getFields() -- 獲得類的所有公共字段
Field getDeclaredField(String name) -- 獲得類聲明的命名的字段,包括private 聲明的和繼承類
Field[] getDeclaredFields() -- 獲得類聲明的所有字段

獲得方法資訊的方法
Method getMethod(String name, Class[] params) -- 使用特定的參數類型,獲得命名的公共方法,name參數指定方法的名字,parameterTypes 參數指定方法的參數類型。
Method[] getMethods() -- 獲得類的所有公共方法
Method getDeclaredMethod(String name, Class[] params) -- 使用特寫的參數類型,獲得類聲明的命名的方法
Method[] getDeclaredMethods() -- 獲得類聲明的所有方法,包括private 聲明的和繼承類
           

反射步驟:

擷取一個對象

  • 擷取類的 Class 對象執行個體

    Class cla = Class.forName("cn.spleated.Car");

  • 根據 Class 對象執行個體擷取 Constructor 對象

    Constructor CarConstructor = cla.getConstructor();

  • 使用 Constructor 對象的 newInstance 方法擷取反射類對象

    Object appleObj = CarConstructor.newInstance();

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import static java.lang.Class.forName;

public class ConstructorDemo {
    public ConstructorDemo(){}
    public ConstructorDemo(int a,int b){
        System.out.println("a="+a+"\nb="+b);
    }
    public static void  main(String args[]) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
            Class cls = forName("ConstructorDemo");
            Class partypes[]=new Class[2];
            partypes[0] = Integer.TYPE;
            partypes[1] = Integer.TYPE;
            Constructor ct = cls.getConstructor(partypes);
            Object arg[] = new Object[2];
            arg[0] = new Integer(37);
            arg[1] = new Integer(14);
            Object ret = ((Constructor) ct).newInstance(arg);
    }
}           

調用某一個方法

  • 擷取方法的 Method 對象

    Method setPriceMethod = cla.getMethod("setPrice", int.class);

  • 利用 invoke 方法調用方法

    setPriceMethod.invoke(appleObj, 14);

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Methodemo {
    public int add(int a,int b){
        return a+b;
    }
    public static void main(String args[]) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class cls = Class.forName("Methodemo");
        Class pro[] = new Class[2];
        pro[0] = Integer.TYPE;
        pro[1] = Integer.TYPE;
        Method me = cls.getMethod("add",pro);
        Methodemo metobj = new Methodemo();
        Object arg[] = new Object[2];
        arg[0] = new Integer(13);
        arg[1] = new Integer(25);
        Object reobj = me.invoke(metobj,arg);
        Integer ret = (Integer) reobj;
        System.out.println(ret.intValue());
    }
}           

Java語言執行系統指令

由JVM建立一個本機程序,加載對應的指令到程序的位址空間中,然後執行該指令。

java.lang.Runtime.getRuntime().exec()

java.lang.ProcessBuilder.start()方

法,其實就是建立一個程序的方法。具體可檢視

Java官方文檔
跟一下代碼流程
  • 進入

    java.lang.Runtime

    類中,

    Runtime類

    的構造器是

    private

    修飾的,無法直接獲得

    Runtime類的執行個體

    ,隻能通過

    getRuntime()

    來間接擷取一個Runtime類的執行個體
  • 跟進

    exec()方法

  • exec()

    底層代碼是調用了

    ProcessBuilder類

  • ProcessBuilder

    類代碼中,

    ProcessBuilder類

    用start方法建立程序。調用

    java.lang.ProcessImpl

    類的start方法,實作建立本機程序,執行系統指令的功能
  • ProcessImpl類

    ,他是繼承自

    Process類

    final類

  • 檢視他的構造器,是private修飾的,無法直接在

    java.lang

    包外,直接調用

    ProcessImpl

    類。
  • ProcessImpl類

    start方法

    ,最後是傳回了一個

    ProcessImpl 類的執行個體

  • 流程圖

分析下上篇文章的通過

getRuntime().exec()

調用計算機

import java.lang.reflect.InvocationTargetException;
public class POC {
    public static void main(String args[]) throws  IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException, ClassNotFoundException {
        Object runtime=Class.forName("java.lang.Runtime")
                .getMethod("getRuntime",new Class[]{})
                .invoke(null);
        Class.forName("java.lang.Runtime")
                .getMethod("exec", String.class)
                .invoke(runtime,"calc.exe");
    }
}           
  • 擷取Runtime類的Class對象
  • 分别擷取Runtime類Class對象的getRuntime方法和exec方法的Method對象
  • 利用getRuntime方法的Method對象,進行invoke調用,獲得Runtime對象執行個體
  • 利用exec方法的Method對象,進行invoke調用,執行系統指令

參考文獻:

https://www.cnblogs.com/chanshuyi/p/head_first_of_reflection.html https://china-jianchen.iteye.com/blog/728774 https://xz.aliyun.com/t/2342