Discussion Locked

Alternate method of discover class name

0 helpful
1 reply
Closed to new repliesThis discussion is closed. It stays readable, but it takes no new replies.

Today I read in our newsletter a way of discovering the classname of a class in a .class file. The concept relied on the knowledge of the .class file format.

Since I've runned into the problem before, here is how I did it: subclass ClassLoader.
lStorage is a byte array loaded with the file.

MyLoader lLoader = new MyLoader(lStorage);
iClass = lLoader.load();
return iClass.getName();

static class MyLoader extends ClassLoader {
byte[] iStorage;

public MyLoader(byte b[]) { iStorage = b;
}

Class load() {
return defineClass(null, iStorage, 0, iStorage.length);
}}

The main difference is that the class is loaded at the same time but you may be short on time and memory. In that case, the newsletter suggestion might be better.

1 reply

by bayard-generationjava

I like the look of it Per. I'll have to try it sometime.

Part of the reasoning for that tip was that it helps show people that class files are not the magic that many of us assume they are.

I used it in an application for the Zaurus a while back and had someone report that it didn't work with some compiled classes. I'm guessing they may have been on JDK 1.4 which probably has a new class specification. My understanding is that Sun tweak it each release.

It's always worked well for me.

Your time-memory point is true. I think the main place I would use my .class file version is if you're looking at many class files. If it's attached to a single FileDialog and you want to show package names instead of file names, yours may be better.

[I'll withhold too much positiveness until I've tried it :) ]

Hen

This discussion is closed to new replies.