有一個抽象類:如何改變Java中抽象類的私有字段?
public abstract class AbstractAny {
private long period;
public void doSomething() {
// blah blah blah
period = someHardcodedValue;
// blah blah blah
}
}
我不想改變抽象類的來源,但需要加上如何在場週期被設定一定的靈活性。是否可以通過重寫方法更改字段的值?例如像:
public class ConcreteSome extends AbstractAny{
@Override
public void doSomething() {
try {
Field p = super.getClass().getDeclaredField("period");
p.setAccessible(true);
p.setLong(this, 10L);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
當我嘗試運行此代碼super.getClass().getDeclaredField("period")
拋出java.lang.NoSuchFieldException: period
修好了,謝謝 – 2009-08-03 14:01:40