Jiapi file

Jiapi file module is used to read java classes into memory. It tries to follow Java Classfile specification closely, so that anyone familiar with the specification, should be able use this artifact easily. This package makes no higher level abstraction to bytecode; It is just an array of bytes. Using jiapi-reflect package allows higher level access to bytecode.


ClassFile cf = ClassFile.parse("JiapiFileSample.class");

List<Field> fields = cf.getFields();
for (Field f : fields) {
   System.out.println("Field: " + f);

List<Method> methods = cf.getMethods();
for (Method m : methods) {
   System.out.println("Method: " + m);

This would result in output

Field: I aField
Method: ()V <init>
Method: ([Ljava/lang/String;)V main

Essential concepts in Java class file format are Constant pool and attributes. ConstantPool holds all the static aspects of class file, like String constants, numerical constants, references to methods and fields, as well as classes. Attributes is a way to attach some data to Class file elements, like methods and fields. This could be for example annotations. Or in case of methods, a "Code" attribute holds all the bytecode of that method.

ConstantPool example

This example just prints out the contents of Constant pool, to get an idea of what is stored int constant pool

ConstantPool cp = cf.getConstantPool();

a fragment of the output looks like this:

16: utf8_info: main
17: utf8_info: ([Ljava/lang/String;)V


33: methodref_info:
  utf8_info: java/io/File(29)
  utf8_info: <init>
  utf8_info: (Ljava/lang/String;)V

Constant pool entries 16 and 17 above tells us the signature of main method of JiapiFileSample class. Entry 33 is saying, that this class is using constructor java.io.File(String) somewhere in the code.