package com.atguigu.spingcloud.bean;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @FileName: ClassStudy
* @Author Steven
* @Date: 2020/3/27
*/
public class ClassStudy {
public static void main(String[] args) throws Exception {
//relectType();
relectClass();
}
/**
* 反射的三种类型
* 1. Class.forName("");全限定名
* 2.XXX.class;
* 3.一个实体类引用getClass();
*/
public static void relectType() throws ClassNotFoundException {
Class aClass1 = Class.forName("com.atguigu.spingcloud.bean.Payment");
Class aClass2 = Payment.class;
Payment payment=new Payment();
Class aClass3 = payment.getClass();
System.out.println(aClass1);
System.out.println(aClass2);
System.out.println(aClass3);
}
/**
* getFields();获取所有public的字段
* getDeclaredFields();获取所有字段
*
* getMethods();获取所有public的方法
* getDeclaredMethod();获取所有public的方法
*
*
* getDeclaredConstructor();获取构造方法
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws InstantiationException
*/
public static void relectClass() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class aClass = Payment.class;
Field[] declaredFields = aClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
declaredField.setAccessible(true);
String name = declaredField.getName();
System.out.println(name);
System.out.println(declaredField);
}
Method[] declaredMethods = aClass.getDeclaredMethods();
for (Method declaredMethod : declaredMethods) {
declaredMethod.setAccessible(true);
String name = declaredMethod.getName();
System.out.println(name);
System.out.println(declaredMethod);
}
Constructor declaredConstructor = aClass.getDeclaredConstructor(Long.class, String.class);
Object steven = declaredConstructor.newInstance(23L, "Steven");
System.out.println(steven);
}
}
反射知识总结
最新推荐文章于 2020-10-15 16:04:53 发布