https://s3-us-west-2.amazonaws.com/secure.notion-static.com/0b72a113-a7d0-456f-b790-29b2f545893d/IMG_0233.jpg

package top.ltyzqhh.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("top.ltyzqhh.Reflection.User");

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

        //获得类的属性
        System.out.println("-----------------------");
        Field[] f1 = c1.getFields();//只能找到public属性
        System.out.println("-----------------------");
        f1 = c1.getDeclaredFields();//找到全部属性
        for (Field field : f1) {
            System.out.println(field);
        }

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

        //获得类的方法
        System.out.println("-----------------------");

        Method[] c1Methods = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method c1Method : c1Methods) {
            System.out.println("getDeclaredMethods:"+c1Method);
        }

        c1Methods = c1.getMethods();//获得本类及其父类的全部public方法
        for (Method c1Method : c1Methods) {
            System.out.println("正常的:"+c1Method);
        }

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

        //获得指定的构造器
        System.out.println("-----------------------");
        Constructor[] constructors = c1.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
         constructors = c1.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println("#"+constructor);
        }

        //获得指定的构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println(declaredConstructor);
    }
}

运行结果

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/35b088ca-edfa-47f2-a57d-e4c8bac1203d/(WML)EGMAWN473505M9ZR.png

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/3a98d63a-bb15-4bd6-9d7d-fdbaae512561/IMG_0234.jpg