簡體   English   中英

以編程方式向項目添加新類

[英]Adding new class to project programmatically

我在Java項目中讀取光盤中的文件。 我在D:/上找到了我的hohoho.java文件,它是文件格式,然后我想把它作為一個類添加到我的主類(Up.java)的現有包中。 它看起來應該是這樣的 - package - > Up.java,Hohoho.java。

它當然應該以編程方式完成。 我將使用這個.java文件及其在我的Up.java中的函數。

你知道這么簡單嗎?

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;

public class Up{

public static void main(String[] args) {

    File root = new File("..\\.");
    File myfile = null;

    try {

        String[] extensions = {"java"};
        boolean recursive = true;

        Collection files = FileUtils.listFiles(root, extensions, recursive);

        for (Iterator iterator = files.iterator(); iterator.hasNext();) {
            File file = (File) iterator.next();
            String path = file.getAbsolutePath();
            System.out.println("File = " + path);

            String[] tokens = path.split("\\\\");

            for (String t : tokens)
              if (t.equals("Hohoho.java")){
                  myfile = file;
              }
            }

        System.out.println("Client class: " + myfile.getAbsolutePath());

    } catch (Exception e) {
        e.printStackTrace();
    }     

   }
}

使用Java Compiler API將源代碼編譯為字節碼。

之后使用ClassLoader將已編譯的類加載到jvm中,並且您可以執行該類的方法。

如果你確定,那個編譯的類實現了特定的接口 - 你可以將它轉換為目標接口並直接調用方法,否則 - 你需要使用Reflection

如果您只需要加載.class文件,根據您的評論,您應該能夠使用以下內容(假設您的設置中沒有安全問題):

    String path = "/path/to/your/classfiles/root/"; //not including the package structure
    ClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + path)}, Up.class.getClassLoader());

    Class clazz = loader.loadClass("foo.Hohoho"); //assuming a package "foo" for that class
    Object loadable = clazz.newInstance();
    Field field = loadable.getClass().getField("someField");  //or whatever - (this assumes you have someField on foo.Hohoho)

    System.out.println(field.get(loadable));

(我在上面刪除了所有異常處理)。 正如@stemm指出的那樣,使用純反射會很痛苦。

此外,從VM內部以盡可能最簡單的方式調用java編譯器的快速測試如下。 所以,如果你確實需要從源頭開始,你可以建立起來:

    String sourcePath = "/path/to/your/javafiles/root/"; 
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int success = compiler.run(null, null, null,  sourcePath + "foo/Loadable.java");//can't get "-sourcepath","path" to go, for some reason.

    System.out.println("success = " + success); //should be 0; Sys err should have details, otherwise

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM