java class 获取包名_通过包名获得本包所有的类名

#### 通过包名获得本包所有的类名

~~~

/*

* @(#)PackageUtil.java 1.00 2006-11-27

* 功能:

* Copyright (c) 2005 Shenzhen Surfilter Network Technology Co.,Ltd. All rights reserved.

*/

package com.hngskj;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.util.ArrayList;

import java.util.List;

import java.util.jar.JarEntry;

import java.util.jar.JarInputStream;

/**

* @since 2006-11-27

* @author wushugen

*

* Modified History:

*

*/

public class Demo1 {

/**

* @param args

* @throws IOException

*/

public static void main(String[] args) throws IOException {

//比如查找java.net包中的类

List cls = getClassInPackage("java.net");

for(String s:cls){

System.out.println(s);

}

}

public static List getClassInPackage(String pkgName) {

List ret = new ArrayList();

String rPath = pkgName.replace('.', '/') + "/";

try {

for (File classPath : CLASS_PATH_ARRAY) {

if(!classPath.exists()) continue;

if (classPath.isDirectory()) {

File dir = new File(classPath, rPath);

if(!dir.exists()) continue;

for (File file : dir.listFiles()) {

if (file.isFile()) {

String clsName = file.getName();

clsName = pkgName+"." +clsName.substring(0, clsName.length() - 6);

ret.add(clsName);

}

}

} else {

FileInputStream fis = new FileInputStream(classPath);

JarInputStream jis = new JarInputStream(fis, false);

JarEntry e = null;

while ((e = jis.getNextJarEntry()) != null) {

String eName = e.getName();

if (eName.startsWith(rPath) && !eName.endsWith("/")) {

ret.add(eName.replace('/', '.').substring(0,eName.length()-6));

}

jis.closeEntry();

}

jis.close();

}

}

} catch (Exception e) {

throw new RuntimeException(e);

}

return ret;

}

private static String[] CLASS_PATH_PROP = { "java.class.path", "java.ext.dirs", "sun.boot.class.path" };

private static List CLASS_PATH_ARRAY = getClassPath();

private static List getClassPath() {

List ret = new ArrayList();

String delim = ":";

if (System.getProperty("os.name").indexOf("Windows") !=-1)

delim = ";";

for (String pro : CLASS_PATH_PROP) {

String[] pathes = System.getProperty(pro).split(delim);

for (String path : pathes)

ret.add(new File(path));

}

return ret;

}

}

~~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值