对不起,我是新来的,但我有并且发出我希望有人可以帮我解决的问题。
这个代码在eclipse中运行得很完美,但在编译后它会说:
java.lang.IllegalArgumentException:URI不是分层的
任何帮助都会被挪用,谢谢!
public void loadMods(String pkg) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException {
List<Class<?>> classes = getClasses(pkg);
for(Class<?> c : classes) {
for (Method m : c.getMethods()) {
Object o = null;
o = c.newInstance();
if (m.getName().contains("load")) {
m.setAccessible(true);
m.invoke(o);
}
}
}
}
public static List<Class<?>> getClasses(String pkg) {
String pkgname = pkg;
List<Class<?>> classes = new ArrayList<Class<?>>();
File directory = null;
String fullPath;
String relPath = pkgname.replace('.', '/');
URL resource = ClassLoader.getSystemClassLoader().getResource(relPath);
if (resource == null) {
throw new RuntimeException("No resource for " + relPath);
}
fullPath = resource.getFile();
try {
directory = new File(resource.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(pkgname + " (" + resource + ") invalid URL / URI.", e);
} catch (IllegalArgumentException e) {
directory = null;
}
if (directory != null && directory.exists()) {
String[] files = directory.list();
for (int i = 0; i < files.length; i++) {
if (files[i].endsWith(".class")) {
String className = pkgname + '.' + files[i].substring(0, files[i].length() - 6);
try {
classes.add(Class.forName(className));
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + className);
}
} else {
String pkgnamex = pkgname + '.' + files[i];
List<Class<?>> classesx = new ArrayList<Class<?>>();
File directoryx = null;
String fullPathx;
String relPathx = pkgnamex.replace('.', '/');
URL resourcex = ClassLoader.getSystemClassLoader().getResource(relPathx);
if (resourcex == null) {
throw new RuntimeException("No resource for " + relPathx);
}
fullPathx = resourcex.getFile();
try {
directoryx = new File(resourcex.toURI());
} catch (URISyntaxException e) {
throw new RuntimeException(pkgnamex + " (" + resourcex + ") invalid URL / URI.", e);
} catch (IllegalArgumentException e) {
directoryx = null;
}
if (directoryx != null && directoryx.exists()) {
String[] filesx = directoryx.list();
for (int ix = 0; ix < filesx.length; ix++) {
if (filesx[ix].endsWith(".class")) {
String classNamex = pkgnamex + '.' + filesx[ix].substring(0, filesx[ix].length() - 6);
try {
classes.add(Class.forName(classNamex));
} catch (ClassNotFoundException e) {
throw new RuntimeException("ClassNotFoundException loading " + classNamex);
}
}
}
}
}
}
}
return classes;
}
答案 0 :(得分:0)
当您从Eclipse中运行代码时,它使用已编译的类(默认情况下在文件夹'target'中)。但是,如果从外部运行代码,则使用Eclipse创建的JAR文件。
当引用JAR中的内容时会出现这个问题,这是由链接的问题解释的。
简而言之:文件系统中的URI在语法上是正确的。引用JAR的URI不再是有效的URI。