1

How to get java.lang.Class from *.class file?

I have a folder whicj contains *.class files. I need to reflect them all to java.lang.Class. I've read this answer and did so, as stated in the first option:

        URL[] classUrl = new URL[1];
        classUrl[0] = new URL("file:" + classFilesFolder);
        URLClassLoader ucl = new URLClassLoader(classUrl);
        Class c = ucl.loadClass("I DON'T KNOW CLASS NAMES HERE!");

The problem is that I don't know names of classes that I'm reflecting. How can I solve this problem?

Community
  • 1
  • 1
Zharro
  • 819
  • 1
  • 11
  • 23

2 Answers2

0

If classFilesFolder is /home/user and the files inside the folder have names like /home/user/com/something/My.class, the class name (including the package) will be com.something.My. So the class name is the full file name, with classFilesFolder removed, then change all forward slashes to dots and remove .class at the end.

John Watts
  • 8,717
  • 1
  • 31
  • 35
  • no, i still can't load Class if I don't specify package name (**models**.myClass). – Zharro Aug 17 '12 at 13:40
  • com.something.My in my example includes the package name. I rewrote the answer to be a little clearer. – John Watts Aug 17 '12 at 13:59
  • I put my class files directly to folder classFilesFolder. These *.class files are intended to be imported. Probably better to abandon imoort *.class files and use the jar files? – Zharro Aug 17 '12 at 14:11
  • 1
    Yes. The mapping of file path to package name is pretty standard, whether inside a jar or outside one. Using a jar rather than separate files should help maintain the relative paths. – John Watts Aug 17 '12 at 14:15
0

You can use asm to parse a class file, and then call getClassName() to find the name.

Tom Anderson
  • 46,189
  • 17
  • 92
  • 133