继承类中的反思

时间:2013-07-11 13:26:59

标签: java inheritance reflection

我使用此方法从类Html中移除String代码:

public void filterStrings() {

    Field[] fields = this.getClass().getDeclaredFields();

    if (fields == null) {
        return;
    }

    for (Field f : fields) {

        if (f.getType() == java.lang.String.class) {

            try {

                String value = (String) f.get(this);

                f.set(this, methodToRemoveHtml(value));

            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

    }

}

工作正常。因为我发现自己将这个方法放在我使用的许多类中,我想我会让所有这些类继承自BaseClass并仅在那里实现该方法。 但是当我这样做时,我会在每次尝试时得到: java.lang.IllegalAccessException: access to field not allowed

  1. 为什么会这样?
  2. 我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

我猜这些字段是私有的,所以只能从包含它们的类中的代码访问它们,而不是超类。

您必须通过调用setAccessible(true);或将其公开或受保护来访问它们。

    for (Field f : fields) {

        if (f.getType() == java.lang.String.class) {

            try {
                f.setAccessible(true); // make field accessible.
                String value = (String) f.get(this);
                // ...

答案 1 :(得分:1)

可能需要致电: f.setAccessible(真);