12 获取类运行时的结构

package annotate;

import java.io.File;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test12 {
    public static void main(String[] args) throws Exception {
        Class c1= Body.class;

        // 获得类的名字
        System.out.println(c1.getName());        // 包名+类名
        System.out.println(c1.getSimpleName()+"====================================");  // 类名

        // 获得全部的属性
              // 获得本类的所有属性;files=c1.getFields():获得本类及父类的所有属性
        Field[] files=c1.getDeclaredFields();  // Fields
        for (Field field:files){
            System.out.println(field);
        }
        // 获得指定的的属性
        Field name=c1.getDeclaredField("name"); // Field
        System.out.println(name);
        System.out.println("==========================================================================");

        // 获得全部的方法
             //获得本类的所有方法;c1.getMethods():获得本类及父类的所有方法
        Method[] methods= c1.getDeclaredMethods();
        for (Method method:methods){
            System.out.println(method);
        }
        System.out.println("=================================");
        // 获得指定的的方法
        Method method= c1.getDeclaredMethod("getAge");
        System.out.println(method);
        Method method2= c1.getDeclaredMethod("setAge", int.class);
        System.out.println(method2);
        System.out.println("=========================================================================");

        // 获得全部的构造器
        Constructor[] constructors=c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        // 获得指定的构造器
        Constructor constructor=c1.getDeclaredConstructor(int.class,int.class,String.class);
        System.out.println(constructor);
    }
}

class Body{
    private int age,id;
    String name;

    public Body(){}
    public Body(int age, int id, String name) {
        this.age = age;
        this.id = id;
        this.name = name;
    }

    public int getAge(){
        return age;
    }
    private void setAge(int age){
        this.age=age;
    }
    public void say(){}
    public void run(){}

}
posted @   被占用的小海海  阅读(0)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示