Search in sources :

Example 1 with FieldAccessor

use of org.fakereplace.reflection.FieldAccessor in project fakereplace by fakereplace.

the class FieldReplacementTransformer method addField.

/**
 * This will create a proxy with a non static field. This field does not
 * store anything, it merely provides a Field object for reflection. Attempts
 * to change and read it's value are redirected to the actual array based
 * store
 */
private static int addField(ClassLoader loader, FieldInfo m, Set<FieldProxyInfo> builder, Class<?> oldClass) {
    int fieldNo = FieldReferenceDataStore.instance().getFieldNo(m.getName(), m.getDescriptor());
    String proxyName = ProxyDefinitionStore.getProxyName();
    ClassFile proxy = new ClassFile(false, proxyName, "java.lang.Object");
    ClassDataStore.instance().registerProxyName(oldClass, proxyName);
    FieldAccessor accessor = new FieldAccessor(oldClass, fieldNo, (m.getAccessFlags() & AccessFlag.STATIC) != 0);
    ClassDataStore.instance().registerFieldAccessor(proxyName, accessor);
    proxy.setAccessFlags(AccessFlag.PUBLIC);
    FieldInfo newField = new FieldInfo(proxy.getConstPool(), m.getName(), m.getDescriptor());
    newField.setAccessFlags(m.getAccessFlags());
    copyFieldAttributes(m, newField);
    try {
        proxy.addField(newField);
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bytes);
        try {
            proxy.write(dos);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        ProxyDefinitionStore.saveProxyDefinition(loader, proxyName, bytes.toByteArray());
        builder.add(new FieldProxyInfo(newField, proxyName, m.getAccessFlags()));
    } catch (DuplicateMemberException e) {
    // can't happen
    }
    return fieldNo;
}
Also used : DuplicateMemberException(javassist.bytecode.DuplicateMemberException) ClassFile(javassist.bytecode.ClassFile) DataOutputStream(java.io.DataOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) FieldAccessor(org.fakereplace.reflection.FieldAccessor) FieldInfo(javassist.bytecode.FieldInfo)

Aggregations

ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 DataOutputStream (java.io.DataOutputStream)1 IOException (java.io.IOException)1 ClassFile (javassist.bytecode.ClassFile)1 DuplicateMemberException (javassist.bytecode.DuplicateMemberException)1 FieldInfo (javassist.bytecode.FieldInfo)1 FieldAccessor (org.fakereplace.reflection.FieldAccessor)1