Bridge Methods From Generic Overrides
A generic override gets a compiler-generated bridge method whose erased Object parameter delegates to the String version, visible via reflection.
Code
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class BridgeProbe {
static class Box<T> {
T value;
void set(T value) { this.value = value; }
}
static class StringBox extends Box<String> {
@Override
void set(String value) { super.set(value); }
}
public static void main(String[] args) {
List<String> lines = new ArrayList<>();
for (Method m : StringBox.class.getDeclaredMethods()) {
String label = m.isBridge() ? "bridge " : "declared";
// 桥接方法:签名被擦除成 set(Object),内部把 Object 转回 String 再委托
lines.add(label + ": " + m.getName()
+ "(" + m.getParameterTypes()[0].getSimpleName() + ")");
}
lines.sort(String::compareTo);
lines.forEach(System.out::println);
}
}Bridge Methods From Generic Overrides: the mechanics
The snippet is organized around the classes BridgeProbe, Box and StringBox and the function main.
for (Method m : StringBox.class.getDeclaredMethods()) drives the iteration over items.
What to watch for
- Any import present resolves to a standard-library module.
Applying it
Entry signature: public static void main(String[] args)
Statements that matter
lines.sort(String::compareTo);
Interactive Tools for This Topic
FAQ
- How do you run Bridge Methods From Generic Overrides?
- Run it as a complete program — compile or interpret the file directly; there is nothing to install first.
Report a problem with this exampleOpens a pre-filled issue on GitHub.