我在官方网站(http://code.google.com/p/reflections/)上找到了此代码,但这不起作用(reflections.getSubTypesOf(requestedClass)
返回空列表)
new Reflections(new ConfigurationBuilder()
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("my.project.prefix")))
.setUrls(ClasspathHelper.forPackage("my.project.prefix"))
.setScanners(new SubTypesScanner(),
new TypeAnnotationsScanner().filterResultsBy(filter),
new ResourcesScanner()));
这是我的代码
@SuppressWarnings({ "rawtypes", "unchecked" })
public Class<? extends ApplicationModuleAbst>
getApplicationModuleAbstSubClass(
ApplicationModuleAbst objInTheSamePckg,
Class<? extends ApplicationModuleAbst> requestedClass) {
String pckName = objInTheSamePckg.getClass().getPackage().getName();
Reflections reflections = new Reflections(new ConfigurationBuilder()
.filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix(pckName)))
.setUrls(ClasspathHelper.forPackage(pckName))
.setScanners(new SubTypesScanner(),
new ResourcesScanner()));
Set<?> applicationModuleAbstSubTypeClasses =
reflections.getSubTypesOf(requestedClass);
Class<? extends ApplicationModuleAbst> appModCls = null;
if (applicationModuleAbstSubTypeClasses.size() == 1) {
appModCls = (Class<? extends ApplicationModuleAbst>)
applicationModuleAbstSubTypeClasses.iterator().next();
} else {
throw new RuntimeException("Exist more than one class that extend " + requestedClass.getName() + " in package " + requestedClass.getPackage().getName());
}
return appModCls;
}
有人知道问题出在哪里?
答案 0 :(得分:0)
简单:它返回空集,因为包中没有类指定的任何子类。
答案 1 :(得分:0)
您可以简单地使用它:
Reflections reflections = new Reflections("my.package.prefix")
并且可能还添加了jboss-vfs类型,如JbossIntegration wiki页面所示:
Vfs.addDefaultURLTypes(
new Vfs.UrlType() {
public boolean matches(URL url) {
return url.getProtocol().equals("vfs");
}
public Vfs.Dir createDir(URL url) {
VirtualFile content;
try {
content = (VirtualFile) url.openConnection().getContent();
} catch (Throwable e) {
throw new ReflectionsException("could not open url connection as VirtualFile [" + url + "]", e);
}
Vfs.Dir dir = null;
try {
dir = createDir(new java.io.File(content.getPhysicalFile().getParentFile(), content.getName()));
} catch (IOException e) { /*continue*/ }
if (dir == null) {
try {
dir = createDir(content.getPhysicalFile());
} catch (IOException e) { /*continue*/ }
}
return dir;
}
Vfs.Dir createDir(java.io.File file) {
try {
return file.exists() && file.canRead() ? file.isDirectory() ? new SystemDir(file) : new ZipDir(new JarFile(file)) : null;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
});