有一个抽象类:如何改变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