我知道这个问题之前已经被问过:
如何使用URLClassLoader加载*.class文件?
但由于缺乏示例,我不太明白。我目前正在开发一个项目,并尝试加载用户给定的 .class 对象,这些对象可以位于计算机上的任何目录中。
//Create URL to hash function class file
URL url_hashFunctionPath = new URL("file:///" + _sHashFunctionFilePath);
//Packet URL to a URL array to be used by URLClassLoader
URL[] urlA_hashFunctionPath = {url_hashFunctionPath};
//Load URL for hash function via a URL class loader
URLClassLoader urlCl_hashFunctionClassLoader = new URLClassLoader(urlA_hashFunctionPath);
//Load user hash function into class to initialize later (TEST: HARD CODE FOR NOW)
m_classUserHashClass = urlCl_hashFunctionClassLoader.loadClass(_sUserHashClassName);
Run Code Online (Sandbox Code Playgroud)
最后一行给了我一个 ClassNotFoundException,根据我的实验&理解用户给定的类函数必须位于类路径中?
PS:第一次发帖,有不懂的地方欢迎指正。
//解决方案
我在 [WillShackleford][1] 的慷慨帮助下得出的解决方案,该解决方案可以在给定的文件路径中加载 .class 文件。有关更多信息,请参阅代码及其给出的注释。
//The absolute file path to …Run Code Online (Sandbox Code Playgroud) Java 9是模块化的,阻止了通过反射基础Java组件的访问.这使得大多数扩展classpath和java.library.path的方法在编程上都无效.怎么做对了?以及如何使其与java.sql.DriverManager和javax.activation兼容?
我编写了一个Java应用程序,我计划在线发布它.每个版本都将使用我制作的秘密序列密钥锁定.
我需要从反编译器等保护我的jar文件.这是我到目前为止所做的:
我做了1〜3步,但我需要知道是否有可能使,抓住从HTTP字节,解密它们,并调用main方法的定制ClassLoader.由于文件是完全加密的(在PHP服务器上保存为bin),我不能使用基本的类加载器.关于步骤8,是否可以从计算机的内存中卸载内容?
该URLClassLoader的有获得的资源作为URL两种功能。一种名为 getResource 并被继承,一种来自 URLClassLoader,名为 findResource。两者都返回一个 URL。它们看起来非常相似,它们之间有什么区别?
getResource 方法注释: 查找具有给定名称的资源。资源是一些数据(图像、音频、文本等),可以通过类代码以独立于代码位置的方式访问。[继续]
findResource 方法注释: 在 URL 搜索路径上查找指定名称的资源。
我有 nio 通道,我的客户端应该从服务器计算机加载类文件。它们的IP范围相同。我有两个在服务器和客户端计算机上常见的接口。以及在服务器计算机上实现接口的类。我在我的客户端机器上使用以下代码,但是当我运行它时会出现ClassNotFoundException。
URL url = new URL("file:///E:/Computing/Master/classes/" );
URLClassLoader ucl = new URLClassLoader(new URL[]{url});
Class clazz = ucl.loadClass("com.counter.controller.Action");
ProcessAlgorithm iAction = (ProcessAlgorithm) clazz.newInstance();
Run Code Online (Sandbox Code Playgroud)
本例中类加载的完整流程是怎样的?
我有一个主要方法,用于创建自定义类加载器并用它实例化一个名为 Test 的类。
public class App {
public static void main(String[] args) throws Exception {
try {
Class.forName("com.mycompany.app2.Test2"); // We ensure that Test2 is not part of current classpath
System.err.println("Should have thrown ClassNotFound");
System.exit(1);
} catch (ClassNotFoundException e) {
// ignore
}
String jar = "C:\\experiments\\classloader-test2\\target\\classloader-test2-1.0-SNAPSHOT.jar"; // Contains Test2
URL[] classPaths = new URL[] { new File(jar).toURI().toURL() };
ClassLoader classLoader = new URLClassLoader(classPaths, App.class.getClassLoader());
Thread.currentThread().setContextClassLoader(classLoader);
Class.forName("com.mycompany.app2.Test2", true, classLoader); // Check that custom class loader can find the wanted class
Test …Run Code Online (Sandbox Code Playgroud) java classloader urlclassloader classnotfoundexception java-17