gpt4 book ai didi

java - 为什么在子类重写时,我通过反射获取基类方法?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:53:03 24 4
gpt4 key购买 nike

我有父类(super class):

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;
}
}

反射(reflection)MyClassImpl作为:

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

我得到两个父类(super class)实现 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.

为什么我得到父类(super class)型实现?有什么我想念的吗?

我需要这个的原因是我反射性地调用了 setValue在基类实现上,我添加了一些特殊的注释注释,当然还有额外的约束。

最佳答案

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

基本上这是必需的,因为 JVM 并不真正了解泛型(至少不是很深入)——为了在 JVM 级别覆盖父类(super class)方法,它必须具有相同的签名。

使用 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

}

关于java - 为什么在子类重写时,我通过反射获取基类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7304293/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com