Situation
A directory full of '.class' files, in appropriate subdirectories according to their class path.
一个充满'.class'文件的目录,在适当的子目录中根据其类路径。
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.
获取每个'.class'文件的Class实例,而不需要使用字符串操作来获取每个文件的“完全限定类名”。
Research
I've seen plenty of ways to get a Class instance from a string.
我已经看到很多方法从字符串中获取Class实例。
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.
“file”参数已经引用了“.class”文件。我已经知道我可以从'file'参数中按下路径,然后得到一个可识别的完全限定类名的东西。如果可以的话,我想避免所有那些乱七八糟的字符串。
I've already seen the following:
我已经看过以下内容:
- How can get an instance from .class file in java
如何从java中的.class文件中获取实例
That's exactly what I don't want to do. And I've seen:
这正是我不想做的事情。我见过:
- How to get an instance of java.lang.Class from a .class file?
如何从.class文件中获取java.lang.Class的实例?
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, *, et.al., I am beginning to wonder if there's any way to do this.
在JavaDocs,*等中咀嚼之后,我开始怀疑是否有任何方法可以做到这一点。
1 个解决方案
#1
2
You could use Javassist for this. From its documentation:
你可以使用Javassist。从其文件:
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();
#1
2
You could use Javassist for this. From its documentation:
你可以使用Javassist。从其文件:
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();