tudoricc
tudoricc

Reputation: 729

Class file parser

I have an assignment where i need to write a Java program that parses a .class file and retrieves things like :

1.name of the .java file

2.implemented interfaces

3.variables

4.constructors

5.methods

I don't have any ideeas where to begin from? For example,what kind of Data I/O structure should I use?

Upvotes: 1

Views: 7347

Answers (5)

madteapot
madteapot

Reputation: 2294

You can use ClassParser which is available in Apache commons library.

Alternatively, load the class using Java normally, and then use the Java Reflection API which provides methods such as getDeclaredFields, getDeclaredMethods, etc.

Upvotes: 3

Jessie Lesbian
Jessie Lesbian

Reputation: 1526

OpenJDK actually comes with an API that lets you parse and manipulate class files programmatically that most programmers don't know about. It is located at the package com.sun.org.apache.bcel.internal.

Upvotes: 0

user666
user666

Reputation: 2013

You don't need any external library, just use java.lang.Class. Write the name of your class:

[NameOfMyClass].class.getDeclaredFields();
[NameOfMyClass].class.getDeclaredConstructors();
[NameOfMyClass].class.getDeclaredMethods();

It's the same for interfaces and many other attributes.

Upvotes: 0

Antimony
Antimony

Reputation: 39461

There are already several libraries for classfile parsing out there. Objectweb ASM is the most popular.

If you have to do it from scratch, that I'd recommend starting by the JVM specification, which explains the binary layout of classfiles in detail. After that, parsing is just a simple matter of programming. I've written a classfile parser before, it's not that hard.

Upvotes: 2

Bahar
Bahar

Reputation: 834

You can use Java Reflection. Here is a good tutorial -->

Java Reflection Tutorial

Upvotes: -1

Related Questions