package summer.reflection;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: reflectdemo3
 * @Description: TODO
 * @Author: Samny
 * @Date: 2020/4/23 14:03
 * @Version: v1.0.0
 * @Description: java.lang.ProccessBuilder
 **/
public class reflectdemo3 {
    public static void main(String[] args) throws InterruptedException {
        System.out.println("Method1!");
        Method1();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("Method2!");
        Method2();
    }
    /**
     * @Author:         samny
     * @CreateDate:     2020/4/23 14:56
     * @UpdateUser:     samny
     * @UpdateDate:     2020/4/23 14:56
     * @UpdateRemark:   修改内容
     * @Version:        v1.0.0
     * @Description:    ProcessBuilder构造方法 public ProcessBuilder(List<String> command)
     */

    public static void Method1(){
        try {
            // 获取对象
            Class cls = Class.forName("java.lang.ProcessBuilder");
            // 实例化对象
            Object ob = cls.getDeclaredConstructor(List.class
            ).newInstance(Arrays.asList("calc"));
            // 执行命令
            cls.getMethod("start").invoke(ob,null);

        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    /**
     * @Author:         samny
     * @CreateDate:     2020/4/23 15:01
     * @UpdateUser:     samny
     * @UpdateDate:     2020/4/23 15:01
     * @UpdateRemark:   修改内容
     * @Version:        v1.0.0
     * @Description:    ProcessBuilder 构造方法 public ProcessBuilder(String... command)
     */
    public static void Method2(){
        try {
            // 获取对象
            Class cls = Class.forName("java.lang.ProcessBuilder");
            // 实例化对象
            // https://xz.aliyun.com/t/7029#toc-3 为什么new String[]{"calc.exe"};不行，可以看起前面文章介绍
            String[][] cls2 = new String[][]{{"calc"}};
            Object ob = cls.getConstructor(String[].class).newInstance(cls2);
            //执行命令
            cls.getMethod("start").invoke(ob,null);

        } catch (ClassNotFoundException | NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }




}
