简体   繁体   English

Java合成方法和桥接方法混淆

[英]Java synthetic method and bridge method confusion

As stated in this Java Tutorial a bridge method implies that it is also a synthetic method.正如本Java 教程中所述,桥接方法意味着它也是一种合成方法。 The question is, is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object, ie, if a method is synthetic does it imply that it is also a bridge method?问题是,是否有可能调用isSynthetic方法返回 true 但isBridge方法对Method对象返回 false,即,如果一个方法是合成的,是否意味着它也是一个桥接方法?

It's not exactly the same but the source code for isSynthetic and isBridge methods looks like below:它并不完全相同,但isSyntheticisBridge方法的源代码如下所示:

static final int SYNTHETIC = 0x00001000;
public boolean isSynthetic() {
    return (getModifiers() & SYNTHETIC) != 0;
}

static final int BRIDGE = 0x00000040;
public boolean isBridge() {
    return (getModifiers() & BRIDGE) != 0;
}

Why isBridge method body is not like return isSynthetic();为什么isBridge方法体不像return isSynthetic(); ? ?

If you are simply looking for an example of such:如果您只是在寻找这样的示例:

Function<String, Integer> func = s -> s.length();

Arrays.stream(DeleteMe.class.getDeclaredMethods())
     .peek(m -> System.out.println(m.getName() + " isSynth : " + m.isSynthetic() + " isBridge : " + m.isBridge()))
     .forEach(System.out::println);

There will be entries like:会有这样的条目:

lambda$0 isSynth : true isBridge : false
lambda$1 isSynth : true isBridge : false

Bridge is synthetic but synthetic is not necessarily bridge.桥是合成的,但合成不一定是桥。 Example:例子:

public class Test {

    public Test clone() {
        return null;
    }

bytecode outline:字节码大纲:

  // access flags 0x1041
  public synthetic bridge clone()Ljava/lang/Object; throws java/lang/CloneNotSupportedException 
   L0
...

is it possible that invocation of isSynthetic method returns true but isBridge method returns false for a Method object是否有可能调用isSynthetic方法返回 true 但isBridge方法对 Method 对象返回 false

Yes, it is possible.对的,这是可能的。

For example, the method AbstractPipeline .例如,方法AbstractPipeline lambda$spliterator$0() is synthetic but is it NOT bridge . lambda$spliterator$0()synthetic但它不是bridge

According to theJVM Spec :根据JVM 规范

  • The ACC_SYNTHETIC flag indicates that this method was generated by a compiler and does not appear in source code ACC_SYNTHETIC标志表示该方法是由编译器生成的,不会出现在源代码中
  • The ACC_BRIDGE flag is used to indicate a bridge method generated by a compiler for the Java programming language. ACC_BRIDGE标志用于指示编译器为 Java 编程语言生成的桥接方法。

So,所以,

  • A bridge method is 100% sure it is synthetic bridge方法 100% 确定它是synthetic
  • A synthetic method is not necessary bridge一种synthetic方法不是必要的bridge

More on bridge method更多关于bridge

Based on this article the bridge method is generated by Java Compiler for type erasure purpose of Java Generics.基于本文bridge方法由 Java Compiler 生成,用于 Java 泛型的类型擦除目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM