繁体   English   中英

带继承的构造函数中的反射(Java)

[英]Reflection in constructor with inheritance (Java)

我在使用继承的类构造函数中进行反射时遇到了麻烦。 具体来说,我想获得所有属性值。

这是一个天真实现的演示,它不起作用:

import java.lang.reflect.Field;

public class SubInitProblem {
  public static void main(String[] args) throws IllegalAccessException {
    Child p = new Child();
  }
}

class Parent {
  public int parentVar = 888888;

  public Parent() throws IllegalAccessException {
    this.showFields();
  }

  public void showFields() throws IllegalAccessException {
    for (Field f : this.getClass().getFields()) {
      System.out.println(f + ": " + f.get(this));
    }
  }
}

class Child extends Parent {
  public int childVar = 999999;

  public Child() throws IllegalAccessException {
    super();
  }
}

这将显示childVar为零:

public int Child.childVar: 0
public int Parent.parentVar: 888888

因为它尚未初始化。

所以我想我不需要直接使用构造函数,而是让构造函数完成然后使用showFields

import java.lang.reflect.Field;

public class SubInitSolution {
  public static void main(String[] args) throws IllegalAccessException {
    SolChild p = SolChild.make();
  }
}

class SolParent {
  public int parentVar = 888888;

  protected SolParent() {
  }

  public static <T extends SolParent> T make() throws IllegalAccessException {
    SolParent inst = new SolParent();
    inst.showFields();
    return (T) inst;
  }

  public void showFields() throws IllegalAccessException {
    for (Field f : this.getClass().getFields()) {
      System.out.println(f + ": " + f.get(this));
    }
  }

}

class SolChild extends SolParent {
  public int childVar = 999999;

  public SolChild() throws IllegalAccessException {
  }
}

但这不起作用,因为make不会为子类返回正确的类型。 (所以问题是new SolParent(); )。

解决这个问题的最佳方法是什么? 我需要所有子类来执行showFields ,但我不能依赖它们明确地执行它。

您的showFields方法需要遍历类层次结构,如下所示:

public void showFields() throws IllegalAccessException {
    Class<?> clz = this.getClass();
    while(clz != Object.class) {
        for (Field f : clz.getDeclaredFields()) {
            f.setAccessible(true);
            System.out.println(f + ": " + f.get(this));
        }
        clz=clz.getSuperclass();
    }
}

请注意,我使用了Class.getDeclaredFields() ,而不是Class.getFields() ,因为后者只处理公共字段。


这就是如何以通用方式构建类:

public static <T extends SolParent> T make(Class<T> type) throws Exception {
    Constructor<T> constructor = type.getDeclaredConstructor();
    constructor.setAccessible(true);
    T inst = constructor.newInstance();
    inst.showFields();
    return inst;
}

请注意,这仅在SolParent的子类型具有公共no-args构造函数(或根本没有构造函数)时才有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM