pet*_*erk 26 java oop overriding
我希望能够确定基类方法是否已被子类重写,因为在调用它之前需要昂贵的设置,并且我们系统中的大多数子类都不会覆盖它.可以使用反射提供的方法句柄进行测试吗?或者是否有其他方法来测试类方法是否被覆盖?
例如
class BaseClass {
void aMethod() { // don nothing }
protected boolean aMethodHasBeenOverridden() {
return( // determine if aMethod has been overridden by a subclass);
}
}
Run Code Online (Sandbox Code Playgroud)
das*_*ght 30
您可以通过检查方法的声明类来完成反射:
class Base {
public void foo() {}
public void bar() {}
}
class Derived extends Base {
@Override
public void bar() {}
}
...
Method mfoo = Derived.class.getMethod("foo");
boolean ovrFoo = mfoo.getDeclaringClass() != Base.class;
Method mbar = Derived.class.getMethod("bar");
boolean ovrBar = mbar.getDeclaringClass() != Base.class;
System.out.println("Have override for foo: "+ovrFoo);
System.out.println("Have override for bar: "+ovrBar);
Run Code Online (Sandbox Code Playgroud)
打印
Have override for foo: false
Have override for bar: true
Run Code Online (Sandbox Code Playgroud)
这可以完成调用getClass().getDeclaredMethod("aMethod"),只有在this声明它的类时返回一些东西.
这是您的方法的实现:
/**
* @return true if the instance's class overrode aMethod
*/
protected boolean aMethodHasBeenOverridden() {
try {
return getClass() != A.class && getClass().getDeclaredMethod("aMethod") != null;
} catch (NoSuchMethodException | SecurityException e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1403 次 |
| 最近记录: |