问题
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