java获取一个类或者一个对象中的所有方法和属性

  • 1.获取 中的所有方法和属性

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

public class Main {
    public static void main(String[] args) {
        Method[]  methods = String.class.getDeclaredMethods();
        Field[] Fields = String.class.getDeclaredFields();
        for (Method method:methods) {
            System.out.print(method.getName());
            System.out.print("-");
            System.out.println(method.getGenericReturnType().getTypeName());
        }
        System.out.println("==========================================");
        for (Field field:Fields) {
            System.out.println(field.getName());
            System.out.print("-");
            System.out.println(field.getGenericType().getTypeName());
        } 
    }
}
  • 2.获取 对象 中的所有方法和属性

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

public class Main {
    public static void main(String[] args) {
        String x = "123";
        Method[]  methods = x.getClass().getDeclaredMethods();
        Field[] Fields = x.getClass().getDeclaredFields();
        for (Method method:methods) {
            System.out.print(method.getName());
            System.out.print("-");
            System.out.println(method.getGenericReturnType().getTypeName());
        }
        System.out.println("==========================================");
        for (Field field:Fields) {
            System.out.println(field.getName());
            System.out.print("-");
            System.out.println(field.getGenericType().getTypeName());
        }
    }
}


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容