美文网首页
java中获取对象的属性和方法

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

作者: 光影墨辰 | 来源:发表于2017-09-30 14:41 被阅读0次
    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中获取对象的属性和方法

          本文链接:https://www.haomeiwen.com/subject/jnngextx.html