以获取Hello.class为例
public class Hello { public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("tes22t2"); for (String arg : args) { System.out.println("hello proms:" + arg); } } }
1.反射
public static void main(String[] args) throws Exception { args = new String[]{"Hello","java疯狂讲义w"}; String progClass = args[0]; String[] progArgs = new String[args.length-1]; System.arraycopy(args , 1 , progArgs, 0 , progArgs.length); // URL[] urls = {new URL("file:")}; // Class<?> clazz = (new URLClassLoader(urls)).loadClass(progClass); Class<?> clazz = Class.forName(progClass); // 获取需要运行的类的主方法 Method main = clazz.getMethod("main" , (new String[0]).getClass()); Object[] argsArray = {progArgs}; main.invoke(null,argsArray); }
2.URLClassLoader
URL[] urls = {new URL("file:")}; Class<?> clazz = (new URLClassLoader(urls)).loadClass(progClass);
3.loadClass
CompileClassLoader ccl = new CompileClassLoader(); // 加载需要运行的类 Class<?> clazz = ccl.loadClass(progClass);
4.覆写findClass
参考
java8--类加载机制与反射(java疯狂讲义3复习笔记)
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Monaco }
span.s1 { text-decoration: underline }
p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 13.0px Monaco }
时间: 2024-10-25 12:38:54