java中获取对象的属性和方法

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class java_clone {
    public static void main(String[] args){
        Person per1 = new Person("mochen",10);
        Class aim = per1.getClass();
        Field[] fields1 = aim.getFields();
        show_field(fields1);
        Field[] fields2 = aim.getDeclaredFields();
        show_field(fields2);
        Method[] methods1 = aim.getMethods();
        show_Method(methods1);
        Method[] methods2 = aim.getDeclaredMethods();
        show_Method(methods2);
    }
    public static void show_field(Field a[]){
        for(Field val : a){
            System.out.print(val.getName() +"    ");
        }
        System.out.println();
    }
    public static void show_Method(Method a[]){
        for(Method val : a){
            System.out.print(val.getName() +"    ");
        }
        System.out.println();
    }
}

class Person {
    public  String name;
    public int age;
    public Person(String name,int age){
        this.name = name;
        this.age = age;
    }
    public  void greet(){
            System.out.println("Hello " + name);
    }
    public String toString(){
        return ("姓名:"+ name + " " + "年龄:" + age);
    }
}

输出结果如下:

         // aim.getFields()打出为空(只可获得public属性的字段);
name    age   //aim.getDeclaredFields;    
toString    greet    wait    wait    wait    equals    hashCode    getClass notify    notifyAll    // aim.getMethods();
toString    greet    // aim.getDeclaredMethods();

你可能感兴趣的:(java中获取对象的属性和方法)