Java Object和Class

来源:互联网 发布:windows me下载地址 编辑:程序博客网 时间:2024/06/05 19:36

Java Object: 拥有一组行为和状态。
Java Class: 描述Object的行为和状态。
通过Class对象,我们能获得Object对象的变量和方法。
下面一个例子:

package ttttt;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.lang.reflect.Modifier;class A {    private int age = 10;    public void doSomething() {    }}public class Test {    public static void main(String[] args) {        A a = new A();        Class<?> clazz = a.getClass();        Field[] fields = clazz.getDeclaredFields();        Method[] methods = clazz.getDeclaredMethods();        for (Field f : fields) {            f.setAccessible(true);            int i = f.getModifiers();            System.out.println("the modifies is private: "+(i==Modifier.PRIVATE));            System.out.println("the tyep is "+f.getGenericType());            try {                System.out.println("the initial value is "+f.getInt(a));            } catch (IllegalArgumentException e) {                e.printStackTrace();            } catch (IllegalAccessException e) {                e.printStackTrace();            }            System.out.println("the field is "+f);        }        for (Method f : methods) {            System.out.println("the method is "+f);        }    }}

另外,可以调用Object.class 和new Object().getClass()获得Class 对象,两者有点不同,前者可以理解是在编译期间,后者是在运行时。

原创粉丝点击