现在有 两个问题1. 怎样在基类中作通用的 用反射取fields的方法?2. 在子类继承后,怎样把本身送入基类的通用方法中供方法中的反射程序取值??

解决方案 »

  1.   

    下面是我写的一个基类测试程序,可这程序用子类继承后根本就不能用,不是这里不合适就是那里不行 -_-!!public class fairy { public void printClassInfo(Class tempClass) {
    try {
    Field FieldList[] = tempClass.getDeclaredFields();
    Field fld = null;
    for (int i = 0; i < FieldList.length; i++) {
    fld = FieldList[i];
    System.out.println("name = " + fld.getName());
    System.out.println("Type = " + fld.getType());
    System.out.println("-----");
    }
    } catch (Throwable e) {
    // TODO 自动生成 catch 块
    System.err.println(e);
    }
    return;
    }}
      

  2.   

    不知道你怎么调用这个printClassInfo的.这样做似乎没有问题,可以显示子类信息:
    今天第一次用java,折腾了半天:public class Test { public int i;
    public void ShowFields()
    {
    Class thisClass=this.getClass();
    Field[] Fields=thisClass.getFields();
    Field field;
    for(int i=0;i<Fields.length ;i++)
    {
    field=Fields[i];
    System.out.print(field.getType().getName());
    System.out.print(" ");
    System.out.println(field.getName());
    }
    }
    public static void main(String[] args) {
    // TODO Auto-generated method stub
    Test test=new Test2();
    test.ShowFields();
    }
    }
    public class Test2 extends Test { public int a;
    }
      

  3.   

    哦!!! 直接在基类中用了 this !! 我怎么没有想到!! 嘿嘿~~~~我再试试
      

  4.   

    WoKao!! 爱死你了我犯了1个错误就是把子类再代回基类处理龙子龙孙在基类中用this就解决了 真好!!程序修改如下 通过!!给分了!!public class fairy { public void printClassInfo() {
    try {
    Class tempClass = this.getClass();
    Field FieldList[] = tempClass.getDeclaredFields();
    Field fld = null;
    for (int i = 0; i < FieldList.length; i++) {
    fld = FieldList[i];
    System.out.println("name = " + fld.getName());
    System.out.println("Type = " + fld.getType());
    System.out.println("-----");
    }
    } catch (Throwable e) {
    // TODO 自动生成 catch 块
    System.err.println(e);
    }
    return;
    }}public class fairyTest extends fairy {
    int a;
    public static void main(String args[]) {
    fairyTest test = new fairyTest();
    test.printClassInfo();
    }
    }