public class Test { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException { URL[] urls = new URL[] {new URL("http://192.168.119.132:8080/images/animal.jar")}; URLClassLoader classLoader = new URLClassLoader(urls); //加载类以后就可以得到 Class 对象了 Class<?> clazz = classLoader.loadClass("com.learn.animal.Dog"); classLoader.close(); //加载完类以后就可以删除了。 //关闭 classLoader, 否则会造成 资源泄露 Resource leak //这里不使用默认的构造器,使用带参数的构造器 获取特殊的构造器 Constructor<?> con = clazz.getDeclaredConstructor(String.class, int.class, int.class); //使用构造器创建对象 Object ob = con.newInstance("小黑",12,50); //在调用 Dog 对象的 say 方法,返回对 Dog 对象自己的描述 Method mtd0 = clazz.getMethod("say", new Class<?>[] {}); String dogSay = (String)mtd0.invoke(ob, new Object[] {}); System.out.println(dogSay); //再使用setter 方法,改变属性 模拟 Dog 对象,逐渐长大,变胖 哈哈! System.out.println("Three years later......"); Method mtd1 = clazz.getMethod("setAge", int.class); mtd1.invoke(ob, 15); Method mtd2 = clazz.getMethod("setWeight", int.class); mtd2.invoke(ob, 70); //注意这些方法是有返回值的! 返回值都是 Object 类型,需要自己强转类型 dogSay = (String)mtd0.invoke(ob, new Object[] {}); System.out.println(dogSay); System.out.println("It's over!"); } }
For the URL resource here, I use a simple nginx server built in the virtual machine. I also built it by following other people's tutorials. It is very simple. A server, haha. However, this is enough for use. If there are no conditions, or if you want to be simpler, you can use the local file system.
Use file:///jar package address
Just replace this.
The jar package used here is also very simple, but I directly typed it into a jar package, which only has class files. I will decompile the following and post the code picture.
This decompilation is not the entire code, but the details are very simple. There is only one say()
method. You can refer to the running screenshot below to complete it.
Then there is the running screenshot. Note that -encoding utf-8 here specifies the encoding character set to be used, because the code executed in cmd may not be compiled if there is Chinese.
The above is the detailed content of How to use the java class loader URLClassLoader. For more information, please follow other related articles on the PHP Chinese website!