上次说的加载jar包,有几个问题没有解决:
1、如果项目包含了其他的jar包如何解决?
2、如何规范上传的jar包的类和方法?
下面就解决一下上面两个问题
一、首先编写被调用的类,这次使用maven工程,并且载入了第三方jar包,阿里巴巴的fastjson包
package com.qunar.hello.hello; import java.util.HashMap; import com.alibaba.fastjson.JSON; public class HelloWorld extends Thread{
public void run(){
HashMap<String, String> m = new HashMap();
m.put("name", "liqiu");
System.out.println(JSON.toJSONString(m));
}
}
二、打一个胖包,修改pom.xml,添加build
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.qunar.hello</groupId>
<artifactId>hello</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging> <name>hello</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.26</version>
</dependency> </dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>
</project>
三、在命令行执行:mvn assembly:assembly
这时候你会发现在target目录出现一个jar:hello-0.0.1-SNAPSHOT-jar-with-dependencies.jar
四、调用这个胖jar包
package com.qunar.studyspring.javajar; import java.net.URL;
import java.net.URLClassLoader;
import java.lang.reflect.Method; public class JavaJar {
public void doJar() {
try {
URL url = new URL("file:/Users/liqiu/Documents/workspace/hello/target/hello-0.0.1-SNAPSHOT-jar-with-dependencies.jar"); // 这里需要重点看URLClassLoader用法,
URLClassLoader loader = new URLClassLoader(new URL[] { url }); // URL跟我们日常见到的格式用法不太一样
Class c = loader.loadClass("com.qunar.hello.hello.HelloWorld"); // 在上面找到并加载jar包后,可以通过此
Thread myObject = (Thread) c.newInstance(); // 函数加载某个类,并使用 newInstance
myObject.run();
} catch (Exception ex) {
System.out.println(ex); }
}
}
五、编写测试类
package com.qunar.studyspring; import org.junit.Test; import com.qunar.studyspring.javajar.JavaJar; public class JarTest { @Test
public void sayHello(){
JavaJar javajar = new JavaJar();
javajar.doJar();
}
}
六、运行的结果是:
{"name":"liqiu"}