【问题标题】:How to create instance of class File?如何创建类文件的实例?
【发布时间】:2016-07-11 22:03:05
【问题描述】:

我已经使用 JFileChooser 获取了一个类文件(比如 Foo.class)并将其存储在 File 类对象中(比如 File a)。 现在我必须使用反射 API 读取 Foo.class 的方法和变量等元数据。 我的问题是,我将它存储在a 中,它只是一个File reference variable。那么如何在文件上使用任何 API。 或任何其他这样做的建议也受到欢迎。

【问题讨论】:

    标签: java class file-io reflection jfilechooser


    【解决方案1】:

    据我了解,首先您需要将类文件转换为 Class 对象,您可以通过 UrlClassLoader 来实现 让我们假设你有 File classFile 和 String className(你也可以弄清楚 className 与文件名完全相同)

     try {
        URLClassLoader classLoader = new URLClassLoader( new URL[]{parent_directory});
        Class<?> clazz = classLoader.loadClass(className);
    } catch (Exception e) {
        // something went wrong..
        e.printStackTrace();
    }
    

    那么现在你有了类对象,你可以使用反射来创建类对象

     try {
        Object instance = clazz.newInstance(); // if there no default constructor you need to get constructors list and create a object
        Method method = clazz.getDeclaredMethod(methodName, String.class);
        method.setAccessible(true);
        method.invoke(instance, argument);
    } catch (Exception e) {
        // something went wrong..
        e.printStackTrace();
    }
    

    注意方法名是未知的,你需要创建一种方法来识别。

    【讨论】:

    • 您传递给URLClassLoaderURL 必须代表基目录而不是类文件。因此,您必须使用类的父目录或其祖先之一,具体取决于所选类的包。
    • 是的,根据您的评论答案已更新
    • 是的..但是loadClass 方法将类的二进制名称作为参数,在我的文件类对象中,我只有该类的绝对路径。有什么解决办法吗? @mithatkonuk
    猜你喜欢
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多