Sangfor华东天勇战队:java8和java17下的反射

文章展示了在JAVA8和Java17环境下使用反射执行命令的代码示例。在JAVA8中,通过`Class.forName`和`getMethod`调用`Runtime.exec`启动计算器。而在Java17中,使用了`MethodHandles.lookup().findVirtual`获取`MethodHandle`来执行相同操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA8下的反射代码

Class<?> runtimeClass = Class.forName("java.lang.Runtime");
Method execMethod = runtimeClass.getMethod("exec", String.class);
Process process = (Process)execMethod.invoke(Runtime.getRuntime(), "calc.exe");
InputStream in = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = reader.readLine())!= null){
    System.out.println(line);
}

在这里插入图片描述
成功弹出计算器

java17下的反射代码

package org.example;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class invoke2 {
    public static void main(String[] args) throws Throwable {
        Class<?> runtimeClass = Class.forName("java.lang.Runtime");
        MethodHandle execMethod = MethodHandles.lookup().findVirtual(runtimeClass, "exec", MethodType.methodType(Process.class, String.class));//查找方法句柄
        Process process = (Process)execMethod.invokeExact(Runtime.getRuntime(),"calc.exe");
        InputStream in = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null){
            System.out.println(line);
        }
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值