How to load an arbitrary java .class file from the filesystem and reflect on it?

南楼画角 提交于 2019-12-12 21:04:32

问题


I want to make a command-line utility that does some operations based on reflection of external class files. I would pass in a path to .class files or source files(possibly wildcards). At some point during the execution, I need to get Class objects for each class, not knowing their package names beforehand. What would it take to do this? What can I look at to get started? I also have access to the classes' source files.

this is in java 1.6.

also, would it be easier to get class objects from the source by using the java compiler API?


回答1:


You will need to create a ClassLoader and use defineClass to create a Class from the file you've read. Add dynamic Java code to your application is an interesting to read about such things, it even describes the compilation of the sources.




回答2:


If you don't know the name of the package, you can find that out by reading the file with an appropriate library, such as ObjectWeb's ASM. In fact, if you are just trying to find out information about the class file, then you might not want to use reflection at all.



来源:https://stackoverflow.com/questions/3103634/how-to-load-an-arbitrary-java-class-file-from-the-filesystem-and-reflect-on-it

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