FileDocCategorySizeDatePackage
JavaClass.javaAPI DocJava SE 6 API23527Tue Jun 10 00:22:18 BST 2008com.sun.org.apache.bcel.internal.classfile

JavaClass

public class JavaClass extends AccessFlags implements Node, Cloneable
Represents a Java class, i.e., the data structures, constant pool, fields, methods and commands contained in a Java .class file. See JVM specification for details. The intent of this class is to represent a parsed or otherwise existing class file. Those interested in programatically generating classes should see the ClassGen class.
version
$Id: JavaClass.java,v 1.2 2005/08/16 19:34:13 jeffsuttor Exp $
see
com.sun.org.apache.bcel.internal.generic.ClassGen
author
M. Dahm

Fields Summary
private String
file_name
private String
package_name
private String
source_file_name
private int
class_name_index
private int
superclass_name_index
private String
class_name
private String
superclass_name
private int
major
private int
minor
private ConstantPool
constant_pool
private int[]
interfaces
private String[]
interface_names
private Field[]
fields
private Method[]
methods
private Attribute[]
attributes
private byte
source
public static final byte
HEAP
public static final byte
FILE
public static final byte
ZIP
static boolean
debug
static char
sep
private transient Repository
repository
In cases where we go ahead and create something, use the default SyntheticRepository, because we don't know any better.
Constructors Summary
public JavaClass(int class_name_index, int superclass_name_index, String file_name, int major, int minor, int access_flags, ConstantPool constant_pool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes, byte source)
Constructor gets all contents as arguments.

param
class_name_index Index into constant pool referencing a ConstantClass that represents this class.
param
superclass_name_index Index into constant pool referencing a ConstantClass that represents this class's superclass.
param
file_name File name
param
major Major compiler version
param
minor Minor compiler version
param
access_flags Access rights defined by bit flags
param
constant_pool Array of constants
param
interfaces Implemented interfaces
param
fields Class fields
param
methods Class methods
param
attributes Class attributes
param
source Read from file or generated in memory?


                                                                                          
           
		           
		        
		           
		           
		           
		    
		         
		         
		        
		     
		             
  
    if(interfaces == null) // Allowed for backward compatibility
      interfaces = new int[0];
    if(attributes == null)
      this.attributes = new Attribute[0];
    if(fields == null)
      fields = new Field[0];
    if(methods == null)
      methods = new Method[0];

    this.class_name_index      = class_name_index;
    this.superclass_name_index = superclass_name_index;
    this.file_name             = file_name;
    this.major                 = major;
    this.minor                 = minor;
    this.access_flags          = access_flags;
    this.constant_pool         = constant_pool;
    this.interfaces            = interfaces;
    this.fields                = fields;
    this.methods               = methods;
    this.attributes            = attributes;
    this.source                = source;

    // Get source file name if available
    for(int i=0; i < attributes.length; i++) {
      if(attributes[i] instanceof SourceFile) {
	source_file_name = ((SourceFile)attributes[i]).getSourceFileName();
	break;
      }
    }

    /* According to the specification the following entries must be of type
     * `ConstantClass' but we check that anyway via the 
     * `ConstPool.getConstant' method.
     */
    class_name = constant_pool.getConstantString(class_name_index, 
						 Constants.CONSTANT_Class);
    class_name = Utility.compactClassName(class_name, false);

    int index = class_name.lastIndexOf('.");
    if(index < 0)
      package_name = "";
    else
      package_name = class_name.substring(0, index);

    if(superclass_name_index > 0) { // May be zero -> class is java.lang.Object
      superclass_name = constant_pool.getConstantString(superclass_name_index,
							Constants.CONSTANT_Class);
      superclass_name = Utility.compactClassName(superclass_name, false);
    }
    else
      superclass_name = "java.lang.Object";    

    interface_names = new String[interfaces.length];
    for(int i=0; i < interfaces.length; i++) {
      String str = constant_pool.getConstantString(interfaces[i], Constants.CONSTANT_Class);
      interface_names[i] = Utility.compactClassName(str, false);
    }
  
public JavaClass(int class_name_index, int superclass_name_index, String file_name, int major, int minor, int access_flags, ConstantPool constant_pool, int[] interfaces, Field[] fields, Method[] methods, Attribute[] attributes)
Constructor gets all contents as arguments.

param
class_name_index Class name
param
superclass_name_index Superclass name
param
file_name File name
param
major Major compiler version
param
minor Minor compiler version
param
access_flags Access rights defined by bit flags
param
constant_pool Array of constants
param
interfaces Implemented interfaces
param
fields Class fields
param
methods Class methods
param
attributes Class attributes

    this(class_name_index, superclass_name_index, file_name, major, minor, access_flags,
	 constant_pool, interfaces, fields, methods, attributes, HEAP);
  
Methods Summary
static final voidDebug(java.lang.String str)

    if(debug)
      System.out.println(str);
  
public voidaccept(com.sun.org.apache.bcel.internal.classfile.Visitor v)
Called by objects that are traversing the nodes of the tree implicitely defined by the contents of a Java class. I.e., the hierarchy of methods, fields, attributes, etc. spawns a tree of objects.

param
v Visitor object

    v.visitJavaClass(this);
  
public com.sun.org.apache.bcel.internal.classfile.JavaClasscopy()

return
deep copy of this class

    JavaClass c = null;

    try {
      c = (JavaClass)clone();
    } catch(CloneNotSupportedException e) {}

    c.constant_pool   = constant_pool.copy();
    c.interfaces      = (int[])interfaces.clone();
    c.interface_names = (String[])interface_names.clone();

    c.fields = new Field[fields.length];
    for(int i=0; i < fields.length; i++)
      c.fields[i] = fields[i].copy(c.constant_pool);

    c.methods = new Method[methods.length];
    for(int i=0; i < methods.length; i++)
      c.methods[i] = methods[i].copy(c.constant_pool);

    c.attributes = new Attribute[attributes.length];
    for(int i=0; i < attributes.length; i++)
      c.attributes[i] = attributes[i].copy(c.constant_pool);

    return c;
  
public voiddump(java.io.File file)
Dump class to a file.

param
file Output file
throws
IOException

    String parent = file.getParent();

    if(parent != null) {
      File dir = new File(parent);
      
      if(dir != null)
	dir.mkdirs();
    }

    dump(new DataOutputStream(new FileOutputStream(file)));
  
public voiddump(java.lang.String file_name)
Dump class to a file named file_name.

param
file_name Output file name
exception
IOException

    dump(new File(file_name));
  
public voiddump(java.io.OutputStream file)
Dump Java class to output stream in binary format.

param
file Output stream
exception
IOException

    dump(new DataOutputStream(file));
  
public voiddump(java.io.DataOutputStream file)
Dump Java class to output stream in binary format.

param
file Output stream
exception
IOException

    file.writeInt(0xcafebabe);
    file.writeShort(minor);
    file.writeShort(major);

    constant_pool.dump(file);
	
    file.writeShort(access_flags);
    file.writeShort(class_name_index);
    file.writeShort(superclass_name_index);

    file.writeShort(interfaces.length);
    for(int i=0; i < interfaces.length; i++)
      file.writeShort(interfaces[i]);

    file.writeShort(fields.length);
    for(int i=0; i < fields.length; i++)
      fields[i].dump(file);

    file.writeShort(methods.length);
    for(int i=0; i < methods.length; i++)
      methods[i].dump(file);

    if(attributes != null) {
      file.writeShort(attributes.length);
      for(int i=0; i < attributes.length; i++)
	attributes[i].dump(file);
    }
    else
      file.writeShort(0);

    file.close();
  
public com.sun.org.apache.bcel.internal.classfile.JavaClass[]getAllInterfaces()
Get all interfaces implemented by this JavaClass (transitively).

    ClassQueue  queue = new ClassQueue();
    ClassVector vec   = new ClassVector();
    
    queue.enqueue(this);
    
    while(!queue.empty()) {
      JavaClass clazz = queue.dequeue();
      
      JavaClass   souper     = clazz.getSuperClass();
      JavaClass[] interfaces = clazz.getInterfaces();
      
      if(clazz.isInterface()) {
	vec.addElement(clazz);
      } else {
	if(souper != null) {
	  queue.enqueue(souper);
	}
      }
      
      for(int i = 0; i < interfaces.length; i++) {
	queue.enqueue(interfaces[i]);
      }
    }
	    
    return vec.toArray();
  
public com.sun.org.apache.bcel.internal.classfile.Attribute[]getAttributes()

return
Attributes of the class.

 return attributes; 
public byte[]getBytes()

return
class in binary format

    ByteArrayOutputStream s  = new ByteArrayOutputStream();
    DataOutputStream      ds = new DataOutputStream(s);

    try {
      dump(ds);
    } catch(IOException e) {
      e.printStackTrace();
    } finally {
      try { ds.close(); } catch(IOException e2) { e2.printStackTrace(); }
    }

    return s.toByteArray();
  
public java.lang.StringgetClassName()

return
Class name.

 return class_name; 
public intgetClassNameIndex()

return
Class name index.

 return class_name_index; 
public com.sun.org.apache.bcel.internal.classfile.ConstantPoolgetConstantPool()

return
Constant pool.

 return constant_pool; 
public com.sun.org.apache.bcel.internal.classfile.Field[]getFields()

return
Fields, i.e., variables of the class. Like the JVM spec mandates for the classfile format, these fields are those specific to this class, and not those of the superclass or superinterfaces.

 return fields; 
public java.lang.StringgetFileName()

return
File name of class, aka SourceFile attribute value

 return file_name; 
public int[]getInterfaceIndices()

return
Indices in constant pool of implemented interfaces.

 return interfaces; 
public java.lang.String[]getInterfaceNames()

return
Names of implemented interfaces.

 return interface_names; 
public com.sun.org.apache.bcel.internal.classfile.JavaClass[]getInterfaces()
Get interfaces directly implemented by this JavaClass.

    String[]    interfaces = getInterfaceNames();
    JavaClass[] classes    = new JavaClass[interfaces.length];

    try {
      for(int i = 0; i < interfaces.length; i++) {
	classes[i] = repository.loadClass(interfaces[i]);
      }
    } catch(ClassNotFoundException e) {
      System.err.println(e);
      return null;
    }

    return classes;
  
public intgetMajor()

return
Major number of class file version.

 return major; 
public com.sun.org.apache.bcel.internal.classfile.MethodgetMethod(java.lang.reflect.Method m)

return
A com.sun.org.apache.bcel.internal.classfile.Method corresponding to java.lang.reflect.Method if any

    for(int i = 0; i < methods.length; i++) {
      Method method = methods[i];

      if(m.getName().equals(method.getName()) &&
	 (m.getModifiers() == method.getModifiers()) &&
	 Type.getSignature(m).equals(method.getSignature())) {
	return method;
      }
    }

    return null;
  
public com.sun.org.apache.bcel.internal.classfile.Method[]getMethods()

return
Methods of the class.

 return methods; 
public intgetMinor()

return
Minor number of class file version.

 return minor; 
public java.lang.StringgetPackageName()

return
Package name.

 return package_name; 
public com.sun.org.apache.bcel.internal.util.RepositorygetRepository()
Gets the ClassRepository which holds its definition. By default this is the same as SyntheticRepository.getInstance();

    return repository;
  
public final bytegetSource()

return
returns either HEAP (generated), FILE, or ZIP

    return source;
  
public java.lang.StringgetSourceFileName()

return
sbsolute path to file where this class was read from

 return source_file_name; 
public com.sun.org.apache.bcel.internal.classfile.JavaClassgetSuperClass()

return
the superclass for this JavaClass object, or null if this is java.lang.Object

    if("java.lang.Object".equals(getClassName())) {
      return null;
    }

    try {
      return repository.loadClass(getSuperclassName());
    } catch(ClassNotFoundException e) {
      System.err.println(e);
      return null;
    }
  
public com.sun.org.apache.bcel.internal.classfile.JavaClass[]getSuperClasses()

return
list of super classes of this class in ascending order, i.e., java.lang.Object is always the last element

    JavaClass   clazz = this;
    ClassVector vec   = new ClassVector();

    for(clazz = clazz.getSuperClass(); clazz != null;
	clazz = clazz.getSuperClass())
    {
      vec.addElement(clazz);
    }

    return vec.toArray();
  
public java.lang.StringgetSuperclassName()

return
Superclass name.

 return superclass_name; 
public intgetSuperclassNameIndex()

return
Class name index.

 return superclass_name_index; 
public booleanimplementationOf(com.sun.org.apache.bcel.internal.classfile.JavaClass inter)

return
true, if clazz is an implementation of interface inter

    if(!inter.isInterface()) {
      throw new IllegalArgumentException(inter.getClassName() + " is no interface");
    }

    if(this.equals(inter)) {
      return true;
    }

    JavaClass[] super_interfaces = getAllInterfaces();

    for(int i=0; i < super_interfaces.length; i++) {
      if(super_interfaces[i].equals(inter)) {
	return true;
      }
    }

    return false;
  
private static final java.lang.Stringindent(java.lang.Object obj)

    StringTokenizer tok = new StringTokenizer(obj.toString(), "\n");
    StringBuffer buf = new StringBuffer();

    while(tok.hasMoreTokens())
      buf.append("\t" + tok.nextToken() + "\n");

    return buf.toString();
  
public final booleaninstanceOf(com.sun.org.apache.bcel.internal.classfile.JavaClass super_class)
Equivalent to runtime "instanceof" operator.

return
true if this JavaClass is derived from teh super class

    if(this.equals(super_class))
      return true;

    JavaClass[] super_classes = getSuperClasses();

    for(int i=0; i < super_classes.length; i++) {
      if(super_classes[i].equals(super_class)) {
	return true;
      }
    }

    if(super_class.isInterface()) {
      return implementationOf(super_class);
    }

    return false;
  
public final booleanisClass()

    return (access_flags & Constants.ACC_INTERFACE) == 0;
  
public final booleanisSuper()

    return (access_flags & Constants.ACC_SUPER) != 0;
  
public voidsetAttributes(com.sun.org.apache.bcel.internal.classfile.Attribute[] attributes)

param
attributes .

    // Debugging ... on/off
    String debug = null, sep = null;
    
    try {
      debug = System.getProperty("JavaClass.debug");
      // Get path separator either / or \ usually
      sep = System.getProperty("file.separator");
    }
    catch (SecurityException e) {
        // falls through
    }

    if(debug != null)
      JavaClass.debug = new Boolean(debug).booleanValue();

    if(sep != null)
      try {
	JavaClass.sep = sep.charAt(0);
      } catch(StringIndexOutOfBoundsException e) {} // Never reached
  
    this.attributes = attributes;
  
public voidsetClassName(java.lang.String class_name)

param
class_name .

    this.class_name = class_name;
  
public voidsetClassNameIndex(int class_name_index)

param
class_name_index .

    this.class_name_index = class_name_index;
  
public voidsetConstantPool(com.sun.org.apache.bcel.internal.classfile.ConstantPool constant_pool)

param
constant_pool .

    this.constant_pool = constant_pool;
  
public voidsetFields(com.sun.org.apache.bcel.internal.classfile.Field[] fields)

param
fields .

    this.fields = fields;
  
public voidsetFileName(java.lang.String file_name)
Set File name of class, aka SourceFile attribute value

    this.file_name = file_name;
  
public voidsetInterfaceNames(java.lang.String[] interface_names)

param
interface_names .

    this.interface_names = interface_names;
  
public voidsetInterfaces(int[] interfaces)

param
interfaces .

    this.interfaces = interfaces;
  
public voidsetMajor(int major)

param
major .

    this.major = major;
  
public voidsetMethods(com.sun.org.apache.bcel.internal.classfile.Method[] methods)

param
methods .

    this.methods = methods;
  
public voidsetMinor(int minor)

param
minor .

    this.minor = minor;
  
public voidsetRepository(com.sun.org.apache.bcel.internal.util.Repository repository)
Sets the ClassRepository which loaded the JavaClass. Should be called immediately after parsing is done.

    this.repository = repository;
  
public voidsetSourceFileName(java.lang.String source_file_name)
Set absolute path to file this class was read from.

    this.source_file_name = source_file_name;
  
public voidsetSuperclassName(java.lang.String superclass_name)

param
superclass_name .

    this.superclass_name = superclass_name;
  
public voidsetSuperclassNameIndex(int superclass_name_index)

param
superclass_name_index .

    this.superclass_name_index = superclass_name_index;
  
public java.lang.StringtoString()

return
String representing class contents.

    String access = Utility.accessToString(access_flags, true);
    access = access.equals("")? "" : (access + " ");

    StringBuffer buf = new StringBuffer(access +
					Utility.classOrInterface(access_flags) + 
					" " +
					class_name + " extends " +
					Utility.compactClassName(superclass_name,
								 false) + '\n");
    int size = interfaces.length;

    if(size > 0) {
      buf.append("implements\t\t");

      for(int i=0; i < size; i++) {
	buf.append(interface_names[i]);
	if(i < size - 1)
	  buf.append(", ");
      }

      buf.append('\n");
    }

    buf.append("filename\t\t" + file_name + '\n");
    buf.append("compiled from\t\t" + source_file_name + '\n");
    buf.append("compiler version\t" + major + "." + minor + '\n");
    buf.append("access flags\t\t" + access_flags + '\n");
    buf.append("constant pool\t\t" + constant_pool.getLength() + " entries\n");
    buf.append("ACC_SUPER flag\t\t" + isSuper() + "\n");

    if(attributes.length > 0) {
      buf.append("\nAttribute(s):\n");
      for(int i=0; i < attributes.length; i++)
	buf.append(indent(attributes[i]));
    }

    if(fields.length > 0) {
      buf.append("\n" + fields.length + " fields:\n");
      for(int i=0; i < fields.length; i++)
	buf.append("\t" + fields[i] + '\n");
    }

    if(methods.length > 0) {
      buf.append("\n" + methods.length + " methods:\n");
      for(int i=0; i < methods.length; i++)
	buf.append("\t" + methods[i] + '\n");
    }

    return buf.toString();