Get the complete structure of the runtime class

Get the complete structure of the runtime class

Obtain the complete structure of the runtime class through reflection

Field Method Constructor Superclass Interface Annotation

  • All interfaces implemented
  • Inherited parent class
  • Full constructor
  • All methods
  • All fields
  • annotation

Case

package Reflection;


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

public class Test07 {
    
    
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
    
    

        Class c1 = Class.forName("Reflection.User");

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

        //获得类的属性
        System.out.println("===============================");
        Field[] fields = c1.getFields();   //只能找到public属性

        Field[] fields1 =c1.getDeclaredFields();   //找到全部的属性
        for (Field field : fields1) {
    
    
            System.out.println(field);
        }

        //获取指定属性的值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);

        //获得类的方法
        System.out.println("===========================");
        Method[] method = c1.getMethods();  //获取本类及其父类的全部public方法
        for (Method method1 : method) {
    
    
            System.out.println("正常的:"+method1);
        }
        Method[]  method1= c1.getDeclaredMethods();  //获取本类的所有方法
        for (Method method2 : method1) {
    
    
            System.out.println(method2);
        }

        //获得指定方法
        //重载
        System.out.println("============获取指定方法==============");
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);
        System.out.println(getName);
        System.out.println(setName);

        //获得公共的构造器  public
        System.out.println("=================================");
        Constructor[] cts1 = c1.getConstructors();
        for (Constructor constructor : cts1) {
    
    
            System.out.println(constructor);
        }
        //获取全部的构造器
        Constructor[] dctts = c1.getDeclaredConstructors();
        for (Constructor dctt : dctts) {
    
    
            System.out.println(dctt);
        }

        //获取指定的构造器
        Constructor constructor111 = c1.getDeclaredConstructor(int.class,String.class,int.class);
        System.out.println("指定:"+constructor111);
    }
}

Guess you like

Origin blog.csdn.net/qq_45162683/article/details/112167475