通过反射来输出一个类的(包括其父类)所有属性

主函数:

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

public class reflec {
    public static void main(String[] args) throws NoSuchMethodException, ClassNotFoundException {
        TestClassEx r = new TestClassEx();

//此处可以写为
//Class<?> c1 = r.getClass();
//或者
//Class<?> c1 = TestClassEx.class; Class
<?> c1 = Class.forName(TestClassEx.class.getName()); while (c1!=null) { for(Field m : c1.getDeclaredFields()){ System.out.println(Modifier.toString(m.getModifiers()) + " " +m.getName() ); } c1=c1.getSuperclass(); System.out.println("----to super class----"); } } }

 

被继承的实体类TestClass:

class TestClass{
    private int i;
    public int j;
    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }

    public int getJ() {
        return j;
    }

    public void setJ(int j) {
        this.j = j;
    }

    public int forSum(){
        return i+j;

    }
}
被继承的实体类TestClass

继承TestClass的子类TestClassEx:

class TestClassEx extends TestClass{
    private String test;
}
继承TestClass的子类

 

运行结果:

private test
----to super class----
private i
public j
----to super class----
----to super class----

Process finished with exit code 0

posted @ 2017-07-28 08:51  kincolle  阅读(273)  评论(0编辑  收藏  举报