如何使用classLoader从加载的类中调用方法? [英] How to call a method from loaded class using classLoader?

查看:89
本文介绍了如何使用classLoader从加载的类中调用方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我使用的代码:

File urlclasspath = new File("C:/Users/ASUS/Desktop/semantics/semantics/bin");
            URL urlarray[] = new URL[1];
            urlarray[0] = urlclasspath.toURI().toURL();

            MyClassLoader mycl = new MyClassLoader(urlarray);

            Class myclass = mycl.loadClass("USAGE");

            Object obj = myclass.newInstance();

我正在加载的类是 用法 ,而我要调用的方法是 main(String [] args)

And the class I'm loading is USAGE and the method I want to call is main(String[] args)

推荐答案

您不需要调用 newInstance()。是否这样做:

You don't need to call newInstance(). Do this:

Class<?> myclass = mycl.loadClass("USAGE"); // get the class
Method m = myclass.getMethod("main", String[].class); // get the method you want to call
String[] args = new String[0]; // the arguments. Change this if you want to pass different args
m.invoke(null, args);  // invoke the method

这篇关于如何使用classLoader从加载的类中调用方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆