简体   繁体   中英

Given only the full path to a .class file, how can I load its Class object?

I'm working on an application that needs to be able to do some analysis on Java code; some through the text and some through reflection. The user should be able to input a directory and the program will pull all .java and .class files from it. I have no problem with the .java files but when I try getting the class of the .class file it doesn't work.

I've looked at using ClassLoader with URL. What I've been able to find so far has given me this

URL url = this.openFile().toURI().toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass(this.path);
return cls;

path is just a string containing the actual path of the .class file in question, eg Users/me/Documents/Application/out/production/MyPackage/MyClass.class . From what I understand from my own reading, this method ties me to knowing the package structure of the input, but in general I don't. All I have is the absolute path of the .class file. Is there a way, just using this path (or some simple transformation of it) that I can load into my program the actual MyClass class object and start doing reflection on it?

You have 2 options:

  1. Use a byte code library to first read the file, so you can find out what the actual class name is.

    Eg in your example it is probably MyPackage.MyClass , but you can't know that from the fully qualified file name.

  2. Implement your own ClassLoader subclass, and call defineClass(byte[] b, int off, int len) .

Recommend using option 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM