views:

714

answers:

6

I'm working on a project where we're doing a lot of remote object transfer between a Java service and clients written in other various languages. Given our current constraints I've decided to see what it would take to generate code based on an existing Java class. Basically I need to take a .class file (or a collection of them) parse the bytecode to determine all of the data members and perhaps getters/setters and then write something that can output code in a different language to create a class with the same structure.

I'm not looking for standard decompilers such as JAD. I need something that can take a .class file and create an object model of it's data members and methods.

+1  A: 

I have used BCEL in the past and it was pretty easy to use. It was a few years ago so there may be something better now.

Apache Jakarta BCEL

Ken
Wow, you actually beat me to answering my own question. That was my default choice, I was going to ask a question and answer it myself and see if anyone else had any better ideas. Thanks.
Mike Deck
A: 

I think javassist might help you too.

http://www.jboss.org/javassist/

I have never had the need of using it, but if you give it a try, would you let us know your comments about it?

Although I think it is more for bytecode manipulation than .class inspection.

OscarRyz
+10  A: 

I've used BCEL and find it really quite awkward. ASM is much better. It very extensively uses visitors (which can be a little confusing) and does not create an object model. Not creating an object model turns out to be a bonus, as any model you do want to create is unlikely to look like a literal interpretation of all the data.

Tom Hawtin - tackline
+1 for ASM over BCEL. Much nicer API.
skaffman
Actually, ASM does provide an object model if you want one. See their Tree API.
Dave L.
After evaluating all the options listed here so far, ASM is definitely the nicest IMHO for inspecting .class files. I agree that the visitor pattern is much cleaner than the BCEL model. Thanks for the tip.
Mike Deck
+1  A: 

From your description, it sounds like simple reflection would suffice. You can discover all of the static structure of the class, as well as accessing the fields of a particular instance.

I would only move on to BCEL if you are trying to translate method instructions. (And if that's what you're trying to automate, good luck!)

erickson
Reflection while a possible solution, is less than ideal. I want to be able to point at an arbitrary .class file and deconstruct it. If I were to use reflection I would have to get the Classloader to load the class before I started working with it.
Mike Deck
A: 

JAD

Heath Borders
JAD is a decompiler, I need something that works programatically.
Mike Deck
+1  A: 

I'm shocked that no one has mentioned ASM yet. It's the best bytecode library your money can buy. Well, ok it's free.

Alex Miller