本帖最后由 a12366456 于 2015-7-25 23:50 编辑
反射代码:- public class Run {
- public Run() {
- // TODO Auto-generated constructor stub
- }
- public static void main(String[] args) {
- try {
- Class<?> clazz = Class.forName("com.drz.jicheng.Zi");
- Constructor<?> constructor = clazz.getConstructor();
- Object zi = constructor.newInstance();
- Field[] fields = clazz.getDeclaredFields();
- System.out.println("fields.length=" + fields.length);
- for (Field field : fields) {
- field.setAccessible(true);
- System.out.println(field.getName() + "=" + field.get(zi));
- }
- Field priField = clazz.getDeclaredField("itt");
- priField.setAccessible(true);
- System.out.println("itt=" + priField.get(zi));
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchMethodException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (SecurityException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
复制代码
父类代码:
- class Fulei_private {
- private int itt = 3;
- public Fulei_private() {
- // TODO Auto-generated constructor stub
- }
- public Fulei_private(int i) {
- this.itt = i;
- }
- public int getItt() {
- return itt;
- }
- public void setItt(int itt) {
- this.itt = itt;
- }
- }
复制代码
子类代码:
- class Zi extends Fulei_private {
- private int ziX = 7;
- public Zi() {
- // TODO Auto-generated constructor stub
- }
- public Zi(int i) {
- super(i);
- // TODO Auto-generated constructor stub
- }
- public int getZiX() {
- return ziX;
- }
- public void setZiX(int ziX) {
- this.ziX = ziX;
- }
- }
复制代码
运行会报告没有这个字段的异常:
java.lang.NoSuchFieldException: itt
at java.lang.Class.getDeclaredField(Class.java:1953)
at com.drz.jicheng.Run.main(Run.java:30)
|
|