1

Situation

A directory full of '.class' files, in appropriate subdirectories according to their class path.

Desire

Get a Class instance for each of those '.class' files, without resorting to string manipulation to get 'fully qualified class names' for each of the files.

Research

I've seen plenty of ways to get a Class instance from a string.

What I'd like to do is avoid strings altogether, and just do something like this:

/**
 * Foo Description Here
 *
 * @parameter file A File instance referring to a '.class' file.
 */
public Class<?> Foo(File file) {
    ...
    return someClassLoader.loadClass(file);
}

The "file" argument already refers to a '.class' file. I already know that I could massage the path from the 'file' argument, and get to something that is recognizably a fully qualified class name. I want to avoid all that messing about with strings if I can.

I've already seen the following:

That's exactly what I don't want to do. And I've seen:

Where the second answer comes close, but leaves open the question of how you get the fully qualified name of the class for the last step. You still have to either mess around with strings, or just arbitrarily name them as you define them.

After munching around in the JavaDocs, StackOverflow, et.al., I am beginning to wonder if there's any way to do this.

Community
  • 1
  • 1
EdwinW
  • 1,007
  • 2
  • 13
  • 32
  • It's unclear to me what the aversion to strings is. If it works, why avoid it? – Makoto Dec 29 '16 at 02:42
  • I suppose because it seems silly to already have a handle on the '.class' file, only to have to go through shenanigans like peeling the classpath directory off the beginning, and the '.class' off the end, then replace all the '/' with '.' to end up with a full qualified class path. That's a lot of extra work to get your hands on something that you've already got a direct reference to. I was hoping that there was a class loader that already accepted 'File' instances, and I just wasn't seeing it. – EdwinW Dec 29 '16 at 02:56

1 Answers1

2

You could use Javassist for this. From its documentation:

ClassPool cp = ClassPool.getDefault();
InputStream ins = an input stream for reading a class file;
CtClass cc = cp.makeClass(ins);

and then convert to class with:

Class clazz = cc.toClass();
EdwinW
  • 1,007
  • 2
  • 13
  • 32
Jochen Bedersdorfer
  • 4,093
  • 24
  • 26
  • Cool! I'll look this over and get back to you. First blush is that it's overkill, but it should do the job. – EdwinW Dec 29 '16 at 02:54
  • If you can't use a regular class loader (which requires you to know the class name), you need to bring in the big guns. – Jochen Bedersdorfer Dec 29 '16 at 02:56
  • 1
    It would indeed do the job, but the team lead shot it down. I'll be doing the string manipulation anyway. Thanks for your help! – EdwinW Dec 29 '16 at 16:41