【问题标题】:File.getClass().getMethod(): how to get .class and methodFile.getClass().getMethod():如何获取 .class 和方法
【发布时间】:2012-08-03 00:15:07
【问题描述】:

我正在使用 JUnit4,我正在尝试设置一个可用于多个相同类的测试(并不重要,为什么它们都是相同的),但我将多个 java 文件传递​​给测试并从中我我正在尝试在方法 eg. list.add(new Object[]{testClass.class, testClass.class.methodName()}); 中创建同时具有 .class 和方法名称的对象(需要两个整数的方法的名称eg. addTwoNumbers(int one, int two),但我收到以下错误

'.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)}); } 上做错了吗?

【问题讨论】:

  • currentFile.getClass() 返回 java.io.File 类,而不是该类文件中包含的任何类。
  • 所有retrieveFiles.listFilesForFolder(folder);返回的文件都是.java文件
  • 没关系。 getClass() 方法返回您调用它的 object 的类。在这种情况下,currentFile 是 java.io.File 的一个实例,所以这就是 getClass() 返回的内容。以这种方式调用它永远不会得到你想要得到的结果。
  • 哦,对了,对不起,我看错了你的评论……你知道如何从.java 文件中获取.class 文件吗?

标签: java file junit


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-31
    • 1970-01-01
    • 2016-10-22
    • 2012-07-12
    • 1970-01-01
    • 2016-11-06
    • 2012-01-10
    相关资源
    最近更新 更多