2012-08-02 22 views
0

我正在使用JUnit4,我試圖設置一個測試,可以用於多個類是相同的(不重要,爲什麼他們都是),但我傳遞了多個Java文件到測試中,並且從中我試圖創建具有.class和方法名稱的對象,方法eg. list.add(new Object[]{testClass.class, testClass.class.methodName()});它工作正常,如果輸入.class的名稱和方法的名稱完全一樣(如上例),但因爲我想爲多個不同的類執行此操作,所以我需要將它們傳入一個循環中,並使用以下代碼list.add(new Object[]{currentFile.getClass(), currentFile.getClass().getMethod(addTwoNumbers,int, int)}其中currentFile是當前正在處理的文件和.getMethod(addTwoNumbers,int, int) addTwoNumbers是需要兩個整數的方法的名稱eg. addTwoNumbers(int one, int two)但我得到以下錯誤File.getClass()。getMethod():如何獲得.class和方法

'.class' expected 

'.class' expected 

unexpected type 
required: value 
found: class 

unexpected type 
required: value 
found: class 

這裏是我完整的代碼

CompilerForm compilerForm = new CompilerForm(); 
RetrieveFiles retrieveFiles = new RetrieveFiles(); 

@RunWith(Parameterized.class) 
public class BehaviorTest { 

    @Parameters 
    public Collection<Object[]> classesAndMethods() throws NoSuchMethodException { 


     List<Object[]> list = new ArrayList<>(); 
     List<File> files = new ArrayList<>(); 
     final File folder = new File(compilerForm.getPathOfFileFromNode()); 
     files = retrieveFiles.listFilesForFolder(folder); 
     for(File currentFile: files){ 
      list.add(new Object[]{currentFile.getClass(), currentFile.getClass().getMethod(addTwoNumbers,int, int)}); 
     } 

     return list; 
    } 
    private Class clazz; 
    private Method method; 

    public BehaviorTest(Class clazz, Method method) { 
     this.clazz = clazz; 
     this.method = method; 
    } 

有誰看到我在做什麼毛病此行list.add(new Object[]{currentFile.getClass(), currentFile.getClass().getMethod(addTwoNumbers,int, int)}); }

+1

currentFile.getClass()返回'java.io.File'類,而不是該類文件中包含的任何類。 – Alex 2012-08-02 15:48:38

+0

'retrieveFiles.listFilesForFolder(folder);'返回的所有文件都是.java文件 – newSpringer 2012-08-02 15:50:07

+0

這並不重要。 getClass()方法返回你調用它的* object *的類。在這種情況下,currentFile是java.io.File的一個實例,這就是getClass()返回的內容。以這種方式調用將永遠得不到你想要得到的結果。 – Alex 2012-08-02 15:54:16

回答

1

我相信你需要首先使用ClassLoader加載文件,然後創建它,以便您可以在類上使用反射。這裏有一個類似的帖子,其答案有更多的信息。 How to load an arbitrary java .class file from the filesystem and reflect on it?

這裏有一些這方面的詳細信息:

A Look At The Java Class Loader

Dynamic Class Loading and Reloading in Java

而這裏使用的URLClassLoader

// Create a File object on the root of the directory containing the class file 
File file = new File("c:\\myclasses\\"); 

try { 
// Convert File to a URL 
URL url = file.toURL();   // file:/c:/myclasses/ 
URL[] urls = new URL[]{url}; 

// Create a new class loader with the directory 
ClassLoader cl = new URLClassLoader(urls); 

// Load in the class; MyClass.class should be located in 
// the directory file:/c:/myclasses/com/mycompany 
Class cls = cl.loadClass("com.mycompany.MyClass"); 
} catch (MalformedURLException e) { 
} catch (ClassNotFoundException e) { 
} 

一個簡單的例子的例子是摘自:

Loading a Class That Is Not on the Classpath