How to create instance of class File?

时间:2016-07-11 22:03:06

标签: java class file-io reflection jfilechooser

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.

1 个答案:

答案 0 :(得分:1)

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

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.