java 枚举 动态_Java中的动态类加载(枚举)

澄清一下,你的问题不是关于“

Java中的动态类加载”,而是关于动态类枚举 – 你知道如何加载类,你只是不知道你想要什么类.

从该页面开始,这里有一些应该有效的示例代码:

public static Class[] getClasses(String pckgname)

throws ClassNotFoundException {

ArrayList classes = new ArrayList();

// Get a File object for the package

File directory = null;

try {

ClassLoader cld = Thread.currentThread().getContextClassLoader();

if (cld == null) {

throw new ClassNotFoundException("Can't get class loader.");

}

String path = '/' + pckgname.replace('.', '/');

URL resource = cld.getResource(path);

if (resource == null) {

throw new ClassNotFoundException("No resource for " + path);

}

directory = new File(resource.getFile());

} catch (NullPointerException x) {

throw new ClassNotFoundException(pckgname + " (" + directory

+ ") does not appear to be a valid package");

}

if (directory.exists()) {

// Get the list of the files contained in the package

String[] files = directory.list();

for (int i = 0; i < files.length; i++) {

// we are only interested in .class files

if (files[i].endsWith(".class")) {

// removes the .class extension

classes.add(Class.forName(pckgname + '.'

+ files[i].substring(0, files[i].length() - 6)));

}

}

} else {

throw new ClassNotFoundException(pckgname

+ " does not appear to be a valid package");

}

Class[] classesA = new Class[classes.size()];

classes.toArray(classesA);

return classesA;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值