1

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?

tudoricc
  • 709
  • 1
  • 12
  • 31
  • can you elaborate a little? – tudoricc Jul 11 '14 at 12:20
  • I looked upon the term you just mentioned and i think i kind of understand – tudoricc Jul 11 '14 at 12:23
  • Hey, sorry for removing my comment so quickly. I hesitated as you mentioned a .class file and I thought you'd have to parse bytecodes. Java "reflection" is an API that allows you to get information of a class or even set accessibility of protected fields and methods of the class. – Unihedron Jul 11 '14 at 14:48

5 Answers5

2

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.

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
madteapot
  • 2,208
  • 2
  • 19
  • 32
2

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.

Antimony
  • 37,781
  • 10
  • 100
  • 107
1

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.

Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74
user666
  • 1,750
  • 3
  • 18
  • 34
  • 3
    -1. Reflection requires the class to be loaded, which may be undesirable or impossible (say, if it conflicts with classes in the program that is doing the introspection, or if its dependencies are not available). Reflection is not a substitute for reading a class file without loading it. – mernst Dec 08 '19 at 04:58
0

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

Java Reflection Tutorial

Bahar
  • 770
  • 5
  • 18
  • 10
    -1. Reflection requires you to actually load and execute the class. Not exactly a classfile parser. – Antimony Jul 11 '14 at 14:55
0

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.

Jessie Lesbian
  • 1,273
  • 10
  • 14