How to create instance of class File?

微笑、不失礼 提交于 2021-02-08 10:41:15

问题


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:


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.



来源:https://stackoverflow.com/questions/38316928/how-to-create-instance-of-class-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!