Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

During navigation of the java.lang.reflect.Method class I came across the method isBridge. Its Javadoc says that it returns true only if the Java spec declares the method as true.

Please help me understand what this is used for! Can a custom class declare its method as a bridge if required?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
220 views
Welcome To Ask or Share your Answers For Others

1 Answer

A bridge method may be created by the compiler when extending a parameterized type whose methods have parameterized arguments.

You can find in this class BridgeMethodResolver a way to get the actual Method referred by a 'bridge method'.

See Create Frame, Synchronize, Transfer Control:

As an example of such a situation, consider the declarations:

class C<T> { abstract T id(T x); }
class D extends C<String> { String id(String x) { return x; } }

Now, given an invocation

C c = new D();
c.id(new Object()); // fails with a ClassCastException

The erasure of the actual method being invoked, D.id(String) differs in its signature from that of the compile-time method declaration, C.id(Object). The former takes an argument of type String while the latter takes an argument of type Object. The invocation fails with a ClassCastException before the body of the method is executed.

Such situations can only arise if the program gives rise to an unchecked warning (§5.1.9).

Implementations can enforce these semantics by creating bridge methods. In the above example, the following bridge method would be created in class D:

Object id(Object x) { return id((String) x); }

This is the method that would actually be invoked by the Java virtual machine in response to the call c.id(new Object()) shown above, and it will execute the cast and fail, as required.

See also Bridge:

as mentioned in the comment, bridge methods are also needed for covariant overriding:

  • In Java 1.4, and earlier, one method can override another if the signatures match exactly.
  • In Java 5, a method can override another if the arguments match exactly but the return type of the overriding method, if it is a subtype of the return type of the other method.

Typically, a method Object clone() can be overridden by a MyObject clone(), but a bridge method will be generated by the compiler:

public bridge Object MyObject.clone();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...