![](/img/trans.png)
[英]How can I load .class files from one project(project 2) to another web project(Project 3) at dynamically runtime in java?
[英]Java reflection: How can I load a class from another project without adding that project or JAR to my classpath?
這是我的情況:我在項目A中有一個類。我想在項目B中的方法中加載該類, 而又不將項目A(或包含該類的JAR)添加到我的項目B類路徑中(我個人不反對這樣做)這樣,但是我必須根據規范進行構建)。
請注意,由於項目A可能安裝在不同的位置,因此我將不知道此類的絕對路徑(我們稱其為“ MyClass”)。 但是,我將知道如何根據當前目錄導航到該目錄,這就是我所做的。
這是我嘗試過的:
// Navigate to the directory that contains the class
File pwd = new File(System.getProperty("user.dir"));
File src = pwd.getAbsoluteFile().getParentFile();
File dir = new File(src.getAbsolutePath() + File.separator + "folder" + File.separator + "src");
// dir is the directory that contains all the packages of project A
// Load the class
URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] {dir.toURI().toURL()});
try {
classLoader.loadClass("com.blahblahblah.MyClass");
} catch (ClassNotFoundException exception) {
}
這將引發ClassNotFoundException。 難道我做錯了什么?
您需要實現一個自定義的類加載器,類似這樣
Class<?> cls = new ClassLoader() {
public java.lang.Class<?> loadClass(String name) throws ClassNotFoundException {
byte[] a = read class bytes from known location
return defineClass(name, b, 0, a.length);
};
}.loadClass("test.MyClass");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.