What's the penalty for Synthetic methods?

女生的网名这么多〃 提交于 2019-11-27 05:15:47
McDowell

Eclipse is warning you that you may be exposing information you think is private. Synthetic accessors can be exploited by malicious code as demonstrated below.

If your code needs to run in a secure VM, it may be unwise to use inner classes. If you can use reflection and have full access to everything, synthetic accessors are unlikely to make a measurable difference.


For example, consider this class:

public class Foo {
  private Object baz = "Hello";
  private class Bar {
    private Bar() {
      System.out.println(baz);
    }
  }
}

The signature for Foo is actually:

public class Foo extends java.lang.Object{
    public Foo();
    static java.lang.Object access$000(Foo);
}

access$000 is generated automatically to let the separate class Bar access baz and will be marked with the Synthetic attribute. The precise names generated are implementation dependent. Regular compilers won't let you compile against this method, but you can generate your own classes using ASM (or similar) like this:

import org.objectweb.asm.*;
public class FooSpyMaker implements Opcodes {
  public static byte[] dump() throws Exception {
    ClassWriter cw = new ClassWriter(0);
    cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "Spy", null, "java/lang/Object",null);
    MethodVisitor ctor = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null);
    ctor.visitCode();
    ctor.visitVarInsn(ALOAD, 0);
    ctor.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V");
    ctor.visitInsn(RETURN);
    ctor.visitMaxs(1, 1);
    ctor.visitEnd();
    MethodVisitor getBaz = cw.visitMethod(ACC_PUBLIC, "getBaz",
        "(LFoo;)Ljava/lang/Object;", null, null);
    getBaz.visitCode();
    getBaz.visitVarInsn(ALOAD, 1);
    getBaz.visitMethodInsn(INVOKESTATIC, "Foo", "access$000",
        "(LFoo;)Ljava/lang/Object;");
    getBaz.visitInsn(ARETURN);
    getBaz.visitMaxs(1, 2);
    getBaz.visitEnd();
    cw.visitEnd();
    return cw.toByteArray();
  }
}

This creates a simple class called Spy that will allow you to call access$000:

public class Spy extends java.lang.Object{
    public Spy();
    public java.lang.Object getBaz(Foo);
}

Using this, you can inspect the value of baz without reflection or any method exposing it.

public class Test {
  public static void main(String[] args) {
    Foo foo = new Foo();
    Spy spy = new Spy();
    System.out.println(spy.getBaz(foo));
  }
}

The Spy implementation requires that it be in the same package as Foo and that Foo isn't in a sealed JAR.

I'm pretty sure the penalty is nothing more than an additional method invocation. In other words, completely irrelevant to almost all use cases.

If it's in a particularly hot path you might get worried, but you should establish with a profiler that this is actually your problem first.

I just turn the warning off.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!