Java – why get base class methods through reflection when subclasses override them?

I have super classes:

class MyClass<T> {
  public void setValue(T value){
    //insert code
  }

  public T getValue(){
    return null;
  }
}@H_502_3@ 
 

那么我有一个具体的推导

class MyClassImp extends MyClass<String> {
  @Override
  public void setValue(String value){
    //insert code
  }

  @Override
  public String getValue(){
    return null;
  }
}@H_502_3@ 
 

在MyClassImpl上反映为:

Class clazz = MyClassImpl.class;
Method[] methods = clazz.getDeclaredMethods();@H_502_3@ 
 

我得到两个超类实现java.lang.Object getValue(),void setValue(java.lang.Object)和java.lang.String getValue(),void setValue(java.lang.String).

根据Class.getDeclaredMethods()的Java文档

Returns an array of Method objects reflecting all the methods declared by the class or interface represented by this Class object. This includes public,protected,default (package) access,and private methods,but excludes inherited methods. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if the class or interface declares no methods,or if this Class object represents a primitive type,an array class,or void. The class initialization method <clinit> is not included in the returned array. If the class declares multiple public member methods with the same parameter types,they are all included in the returned array.

为什么我得到超级类型的实现?
有没有我失踪的东西?

我需要这个的原因是我反思地在基类实现中调用setValue,我已经添加了一些特殊的注释注释,当然还有其他的约束.

Solution

This is because the compiled class actually declares setValue (object) The method will be converted to String and then called strongly typed method. Similarly, getValue (object) calls getValue (string)

Basically, this is necessary because the JVM really doesn't know generics (at least not in a profound way) – in order to override superclass methods at the JVM level, it must have the same signature

Look at the javap - C myclassimp class, and you will see additional synthesis methods:

public java.lang.Object getValue();
  Code:
   0:   aload_0
   1:   invokevirtual   #3; //Method getValue:()Ljava/lang/String;
   4:   areturn

public void setValue(java.lang.Object);
  Code:
   0:   aload_0
   1:   aload_1
   2:   checkcast       #4; //class java/lang/String
   5:   invokevirtual   #5; //Method setValue:(Ljava/lang/String;)V
   8:   return

}@H_502_3@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>