栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 通过反射调用main方法

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 通过反射调用main方法

java 通过反射调用main方法

我们可以通过绝对路径让URLClassLoader,加载一个程序外部的 .class文件并调用其main方法

public class Test {
    public static void main(String[] args) throws InterruptedException {
        Test test = new Test();
        test.say();
    }

    public void say() throws InterruptedException {
        int i = 0;
        while (true) {
            i++;
            if (i >= 100) {
                break;
            }
            Thread.sleep(1000);
            System.out.println("hello");
        }
    }
}
package com;

import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

public class Hello {
    public static void main(String[] args)
            throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException, MalformedURLException {
        File file = new File("../Test.class");
        URL[] urls = new URL[1];
        urls[0] = file.toURL();
        URLClassLoader classLoader = new URLClassLoader(urls);
        System.out.println(classLoader);
        Class mClass = classLoader.loadClass("Test");
        Object test = mClass.newInstance();
        Method m1 = mClass.getMethod("main", String[].class);
        m1.invoke(null, (Object) new String[] { "a", "b", "c" });
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/781648.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号