加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么当子类覆盖它们时,通过反射获得基类方法?

发布时间:2020-12-14 05:56:00 所属栏目:Java 来源:网络整理
导读:我有超级班: class MyClassT { public void setValue(T value){ //insert code } public T getValue(){ return null; }} 那么我有一个具体的推导 class MyClassImp extends MyClassString { @Override public void setValue(String value){ //insert code }
我有超级班:
class MyClass<T> {
  public void setValue(T value){
    //insert code
  }

  public T getValue(){
    return null;
  }
}

那么我有一个具体的推导

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

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

在MyClassImpl上反映为:

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

我得到两个超类实现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,我已经添加了一些特殊的注释注释,当然还有其他的约束.

解决方法

这是因为编译的类实际上声明了setValue(Object).该方法将转换为String,然后调用强类型方法.同样getValue(Object)调用getValue(String).

基本上这是必需的,因为JVM真的不知道泛型(至少不是以深刻的方式) – 为了在JVM级别覆盖超类方法,它必须具有相同的签名.

看看javap -c MyclassImp的类,你会看到额外的合成方法:

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

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读