mockit.asm.FieldWriter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of jmockit Show documentation
Show all versions of jmockit Show documentation
JMockit is a Java toolkit for automated developer testing.
It contains mocking/faking APIs and a code coverage tool, supporting both JUnit and TestNG.
The mocking APIs allow all kinds of Java code, without testability restrictions, to be tested
in isolation from selected dependencies.
package mockit.asm;
import javax.annotation.*;
/**
* A {@link FieldVisitor} that generates Java fields in bytecode form.
*/
final class FieldWriter extends FieldVisitor
{
/**
* The index of the constant pool item that contains the name of this field.
*/
@Nonnegative private final int name;
/**
* The index of the constant pool item that contains the descriptor of this field.
*/
@Nonnegative private final int desc;
@Nullable private final SignatureWriter signatureWriter;
/**
* The index of the constant pool item that contains the constant value of this field.
*/
@Nonnegative private final int value;
/**
* Initializes a new Field Writer.
*
* @param cw the class writer to which this field must be added.
* @param access the field's access flags (see {@link Opcodes}).
* @param name the field's name.
* @param desc the field's descriptor (see {@link JavaType}).
* @param signature the field's signature.
* @param value the field's constant value.
*/
FieldWriter(
@Nonnull ClassWriter cw, int access, @Nonnull String name, @Nonnull String desc, @Nullable String signature, @Nullable Object value
) {
cp = cw.cp;
this.access = access;
this.name = cp.newUTF8(name);
this.desc = cp.newUTF8(desc);
signatureWriter = signature == null ? null : new SignatureWriter(cp, signature);
this.value = value == null ? 0 : cp.newConstItem(value).index;
createMarkerAttributes(cw.version);
}
@Nonnull @Override
public AnnotationVisitor visitAnnotation(@Nonnull String desc) {
return addAnnotation(desc);
}
/**
* Returns the size of this field.
*/
@Nonnegative
int getSize() {
int size = 8 + getMarkerAttributesSize() + getAnnotationsSize();
if (value != 0) {
cp.newUTF8("ConstantValue");
size += 8;
}
if (signatureWriter != null) {
size += signatureWriter.getSize();
}
return size;
}
/**
* Puts the content of this field into the given byte vector.
*/
@Override
void put(@Nonnull ByteVector out) {
putAccess(out, 0);
out.putShort(name);
out.putShort(desc);
int attributeCount = getAttributeCount();
out.putShort(attributeCount);
if (value != 0) {
out.putShort(cp.newUTF8("ConstantValue"));
out.putInt(2).putShort(value);
}
putMarkerAttributes(out);
if (signatureWriter != null) {
signatureWriter.put(out);
}
putAnnotations(out);
}
@Nonnegative
private int getAttributeCount() {
int attributeCount = getMarkerAttributeCount();
if (value != 0) {
attributeCount++;
}
if (signatureWriter != null) {
attributeCount++;
}
if (annotations != null) {
attributeCount++;
}
return attributeCount;
}
}