2012-08-02 74 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