使用URLClassLoader加载类时出现java

使用URLClassLoader加载类时出现java

我有一个看起来像这样的JAR文件:

MacBook@ ~/workspace-sync/mparnisa_dynamodb2/out/artifacts/dynamodb $ jar tf dynamodb.jar | head
META-INF/MANIFEST.MF
mparnisa-dynamodb-table.json
com/
com/mparnisa/
com/mparnisa/dynamodb/
com/mparnisa/dynamodb/table/
com/mparnisa/dynamodb/table/ResourceModel$ResourceModelBuilder.class
com/mparnisa/dynamodb/table/ResourceModel.class
com/amazonaws/AmazonServiceException.class
// and many more...


我想从IntelliJ项目中创建一个ResourceModel实例,如下所示:

package com.mparnisa.dynamodb.table;

@com.fasterxml.jackson.annotation.JsonAutoDetect(fieldVisibility = com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.ANY, getterVisibility = com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE, setterVisibility = com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility.NONE)
public class ResourceModel {


所以在我的代码中,我这样写:

File file  = new File("/Users/mparnisa/workspace-sync/mparnisa_dynamodb2/out/artifacts/dynamodb/dynamodb.jar");

URL url = file.toURI().toURL();
URL[] urls = new URL[]{url};

ClassLoader urlClassLoader = new URLClassLoader(urls);

String resourceModelClassName = "com.mparnisa.dynamodb.table.ResourceModel";

Class<?> resourceModelClass = urlClassLoader.loadClass(resourceModelClassName);


但最后一行抛出异常:

java.lang.ClassNotFoundException: com.mparnisa.dynamodb.table.ResourceModel

最佳答案

找到该类但静态初始化失败时,也会引发NoClassDefFound。在这种情况下,程序启动时日志中应该有一个更有用的例外。

关于java - 使用URLClassLoader加载类时出现java.lang.ClassNotFoundException,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60766930/

10-10 17:18