如何创建类File的实例? [英] How to create instance of class File?

查看:91
本文介绍了如何创建类File的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用JFileChooser获取了一个类文件(例如Foo.class),并将其存储在File类对象(例如File a)中. 现在,我必须使用反射API读取元数据,例如Foo.class的方法和变量. 我的问题是,我将其存储在a中,它只是一个File reference variable.因此,如何在文件上使用任何API. 或其他任何建议.

I've taken a class file(say Foo.class) using JFileChooser and stored it in a File class object(say File a). now I've to read metadata like methods and variables of this Foo.class using reflection APIs. My question is that, I've stored it in a, which is just a File reference variable. So how can I use any API on a File. or any other suggestion for doing so are also welcomed.

推荐答案

据我了解,首先您需要将类文件转换为Class对象,您可以通过UrlClassLoader进行操作 假设您有File classFile和String className(也可以找出与文件名完全相同的className)

as i understand,first of all you need to convert class file to Class object you can do that via UrlClassLoader Lets Assume you have File classFile and String className ( also you can figure it out className exactly same with filename)

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

这时您现在有了Class Object,并且可以使用反射来创建Class Object

then now you have Class Object and you can use reflection to create Class Object

 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();
}

请注意,方法名称未知,您需要创建一种识别方法.

Note that method name is unknown you need to create a way to identifying.

这篇关于如何创建类File的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆