Java – determine whether one method overrides another that uses reflection?
See English answer > java: how to find if a method is overridden from base class? 8
I find that the only solution usually considers a method to be covered if class B can be assigned from Class A and if method a has the same signature as method B But it doesn't cover every situation!
For example, I would like to deal with this situation:
interface Foo<T> { void doStuff(T arg); } class FooImpl implements Foo<String> { public void doStuff(String args) { //Is overriden! } }
I also want to check that method B is actually visible to method a (package scope, etc.)
Have you ever experienced a reliable method to determine whether a method is overwritten?
thank you
Solution
Is there an existing answer to determine whether a method is overridden if no generics are involved
Java will completely remove generic types because of type erasure So the bytecode will be:
class FooImpl implements Foo<java.lang.String> { FooImpl(); Code: 0: aload_0 1: invokespecial #10 // Method java/lang/Object."<init>":()V 4: return public void doStuff(java.lang.String); Code: 0: return public void doStuff(java.lang.Object); Code: 0: aload_0 1: aload_1 2: checkcast #21 // class java/lang/String 5: invokevirtual #23 // Method doStuff:(Ljava/lang/String;)V 8: return }
There are two dostuff methods It is a bridge method It only performs type conversion and calls void dostuff (Java. Lang. string), so in fact void dostuff (Java. Lang. string) is not overwritten, but void dostuff (Java. Lang. object) is When you use polymorphism, such as:
Foo foo = new FooImpl(); foo.doStuff("ABC")
It actually calls void dostuff (Java. Lang. object) So if you use the above link to detect whether void dostuff (Java. Lang. object) is overwritten, it will report yes
public static void main(java.lang.String[]); Code: 0: new #1 // class FooImpl 3: dup 4: invokespecial #22 // Method "<init>":()V 7: astore_1 8: aload_1 9: ldc #23 // String ABC 11: invokeinterface #25,2 // InterfaceMethod Foo.doStuff:(Ljava/lang/Object;)V 16: return