JAVA 反射基本使用

163 阅读1分钟

基本类

package com.user;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

@Component
@Controller
public class User {
    private Long age;
    private String name;
    public  String sex;


    public String  getName(){
        return this.name;
    }


    private String getSex(){
        return sex;
    }

    public void speakCity(String name){
        System.out.println(name);
    };

    
}

test方法

@Test
void ann() {
    //获取UserClass对象
    Class<User> userClass = User.class;
    Annotation[] declaredAnnotations = userClass.getDeclaredAnnotations(); //获取全部注解
    Annotation[] annotations = userClass.getAnnotations(); //获取public注解
    AnnotatedType[] annotatedInterfaces = userClass.getAnnotatedInterfaces(); //类型为null
    System.out.println(Arrays.toString(annotatedInterfaces));
}

@Test
void methode() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
    Class<User> userClass = User.class;
    User user = userClass.newInstance();
    Method[] declaredMethods = userClass.getDeclaredMethods(); //全部方法DeclareMethods
    Method[] methods = userClass.getMethods();//获取public方法 - 会包含Object的方法
    Method enclosingMethod = userClass.getEnclosingMethod(); //todo 没搞懂  直接翻译 ~ 是封闭的方法 或者说内部类
    for (Method declaredMethod : declaredMethods) {
        Type[] genericParameterTypes = declaredMethod.getGenericParameterTypes(); //获取方法参数类型 ~
        Type genericReturnType = declaredMethod.getGenericReturnType();//获取返回类型
        Class<?>[] exceptionTypes = declaredMethod.getExceptionTypes();//获取异常类型
        System.out.println("方法名称:"+ declaredMethod.getName() +"我是返回类型:"+ genericReturnType);
        System.out.println(declaredMethod.getName());
    }
    //调用名称  - 调用参数类型class
    Method speakCity = userClass.getMethod("speakCity", String.class); //只能获取可以访问的东西 如果没有抛出异常
    //方法调用  - 传入 对象,参数
    speakCity.invoke(user,"你好");

    System.out.println(enclosingMethod);
}

@Test
void constructors() throws InvocationTargetException, InstantiationException, IllegalAccessException {
    Class<User> userClass = User.class;
    Constructor<?>[] declaredConstructors = userClass.getDeclaredConstructors();//获取构造器
    for (Constructor<?> declaredConstructor : declaredConstructors) {
        Object o = declaredConstructor.newInstance(); //创建对象
        declaredConstructor.getGenericParameterTypes(); //获取对象参数
    }
}