首先,当知道当前需要的类所在的包地址,例如:/com/zhouxf/jarread/dos/impl 这样一个目录,当项目被打包成test.jar ,你如何获取到这个包地址下的所有的class文件呢。
一般要获取都是在某一个类里面,例如factory或者相关的manager里面。在相对的目录中获取所需要的class文件,并且实例化这些class的过程。
例子如下:
首先定义一个球的接口:
然后实现接口
然后打包代码test.jar, 把他导入到工程。
下面写一个类来读取jar包;
这样,就能打印出
一般要获取都是在某一个类里面,例如factory或者相关的manager里面。在相对的目录中获取所需要的class文件,并且实例化这些class的过程。
例子如下:
首先定义一个球的接口:
public interface Ball {
/**
* 输出球类型
*/
void getName();
} 然后实现接口
public class BasketBall implements Ball {
public void getName() {
// TODO Auto-generated method stub
System.out.println("BasketBall.........");
}
}
public class FootBall implements Ball {
public void getName() {
// TODO Auto-generated method stub
System.out.println("FootBall.........");
}
}然后打包代码test.jar, 把他导入到工程。
下面写一个类来读取jar包;
/**
* 读取类,然后输出相关信息
*
* @author xiaofeng.zhouxf
*/
public class JarReader {
private Map map;
private final String pointClass = ".class";
private final String slash = "/";
private final String point = ".";
private final String javaSeparator = "\\\\";
private final String packagePath = "/com/zhouxf/jarread/dos/impl";
private final String jarName = "test.jar"; ;
public void test() throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
// 用来存放包下class文件
map = new HashMap();
// 取得资源所在目录
URL url = this.getClass().getResource(packagePath);
String resourcePath = url.getFile();
resourcePath = resourcePath.substring(1);
int index = resourcePath.indexOf(packagePath);
String diskPath = resourcePath.substring(0, index);
resourcePath = resourcePath.replace(slash, javaSeparator);
diskPath = diskPath.replace(slash, javaSeparator);
// 取得jar包对象
JarFile file = new JarFile((diskPath + javaSeparator + jarName));
// 判断和获取jar包中的entry
Enumeration<JarEntry> entries = file.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
String entryName = entry.getName();
// System.out.println("entryName:" + entryName);
if (entryName.indexOf(packagePath.substring(1)) != -1) {
String classPath = entryName.substring(0, entryName.indexOf(pointClass)).replace(slash, point);
Ball ball = (Ball) Class.forName(classPath).newInstance();
ball.getName();
}
}
}
public static void main(String... strings) {
JarReader reader = new JarReader();
try {
reader.test();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}这样,就能打印出
BasketBall.........
FootBall.........
2102

被折叠的 条评论
为什么被折叠?



