|
|
|
|
|
|
|
|
writes the contents of the class file to a given |
|
|
writes the contents of the class file to a given |
|
|
<code>DataOutputStream</code>. |
|
|
<code>DataOutputStream</code>. |
|
|
|
|
|
|
|
|
|
|
|
<p>You can create a new class file from scratch. For example, |
|
|
|
|
|
<blockquote><pre> |
|
|
|
|
|
ClassFile cf = new ClassFile(false, "test.Foo", null); |
|
|
|
|
|
cf.setInterfaces(new String[] { "java.lang.Cloneable" }); |
|
|
|
|
|
|
|
|
|
|
|
FieldInfo f = new FieldInfo(cf.getConstPool(), "width", "I"); |
|
|
|
|
|
f.setAccessFlags(AccessFlag.PUBLIC); |
|
|
|
|
|
cf.addField(f); |
|
|
|
|
|
|
|
|
|
|
|
cf.write(new DataOutputStream(new FileOutputStream("Foo.class"))); |
|
|
|
|
|
</pre></blockquote> |
|
|
|
|
|
|
|
|
|
|
|
<p>this code generates a class file <code>Foo.class</code> that contains |
|
|
|
|
|
the implementation of the following class: |
|
|
|
|
|
|
|
|
|
|
|
<blockquote><pre> |
|
|
|
|
|
package test; |
|
|
|
|
|
class Foo implements Cloneable { |
|
|
|
|
|
public int width; |
|
|
|
|
|
} |
|
|
|
|
|
</pre></blockquote> |
|
|
|
|
|
|
|
|
<p><br> |
|
|
<p><br> |
|
|
|
|
|
|
|
|
<a name="member"> |
|
|
<a name="member"> |
|
|
|
|
|
|
|
|
To recompute the maximum stack depth of a method body, |
|
|
To recompute the maximum stack depth of a method body, |
|
|
call <code>computeMaxStack()</code> in <code>CodeAttribute</code>. |
|
|
call <code>computeMaxStack()</code> in <code>CodeAttribute</code>. |
|
|
|
|
|
|
|
|
|
|
|
<p><code>Bytecode</code> can be used to construct a method. |
|
|
|
|
|
For example, |
|
|
|
|
|
|
|
|
|
|
|
<blockquote><pre> |
|
|
|
|
|
ClassFile cf = ... |
|
|
|
|
|
Bytecode code = new Bytecode(cf.getConstPool()); |
|
|
|
|
|
code.addAload(0); |
|
|
|
|
|
code.addInvokespecial("java/lang/Object", MethodInfo.nameInit, "()V"); |
|
|
|
|
|
code.addReturn(null); |
|
|
|
|
|
code.setMaxLocals(1); |
|
|
|
|
|
|
|
|
|
|
|
MethodInfo minfo = new MethodInfo(cf.getConstPool(), MethodInfo.nameInit, "()V"); |
|
|
|
|
|
minfo.setCodeAttribute(code.toCodeAttribute()); |
|
|
|
|
|
cf.addMethod(minfo); |
|
|
|
|
|
</pre></blockquote> |
|
|
|
|
|
|
|
|
|
|
|
<p>this code makes the default constructor and adds it to the class specified |
|
|
|
|
|
by <code>cf</code>. The <code>Bytecode</code> object is first converted into |
|
|
|
|
|
a <code>CodeAttribute</code> object and then added to the method specified |
|
|
|
|
|
by <code>minfo</code>. The method is finally added to a class file <code>cf</code>. |
|
|
|
|
|
|
|
|
<p><br> |
|
|
<p><br> |
|
|
|
|
|
|
|
|
<a name="annotation"> |
|
|
<a name="annotation"> |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<hr> |
|
|
<hr> |
|
|
Java(TM) is a trademark of Sun Microsystems, Inc.<br> |
|
|
Java(TM) is a trademark of Sun Microsystems, Inc.<br> |
|
|
Copyright (C) 2000-2014 by Shigeru Chiba, All rights reserved. |
|
|
|
|
|
|
|
|
Copyright (C) 2000-2015 by Shigeru Chiba, All rights reserved. |
|
|
</body> |
|
|
</body> |
|
|
</html> |
|
|
</html> |