开发者

Reading Bytecode from the Classpath

I've defined my own classloader, which needs to read bytecode from the classpath, enhance it, and define the class. My initial implementation had a line that looked like this:

getResourceAsStream(name.replaceAll("\\.", File.separator)+".class");

But I appear to have out-grown that hack. I'm running into boundary conditions like nested subclasses, which this line doesn't hand开发者_StackOverflow社区le properly.

What is the correct/accepted solution?

Thanks!


If name is the classes binary name, then the resource file name would conventionally be:

    separator + name.replaceAll("\\.", separator) + ".class"

The binary name of a class is the value used in bytecode files, and returned by Class.getName().

Note that the resource name separator is not necessarily the same as File.separator. For example, if the classloader is loading from a JAR file, then the separator is defined by the JAR file API, not by file system conventions.

Provided that you use the binary name for nested / anonymous classes, this should all work. However, the mapping of fully qualified class names to binary class names is compiler specific, and not easy to reproduce automatically. (You'd need to reproduce the scheme that the compiler uses to allocate the $n name components, and that would require access to the source code.) So getting your classloader to understand fully qualified names would be hard. But that's OK, because normal classloaders don't ...

Finally, note that I said "conventionally". In theory, you can implement whatever class file naming scheme you feel like, so long as you can figure out how to do the mapping consistently.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜