在JDK中,主要由以下类来实现Java反射机制

在JDK中,主要由以下类来实现Java反射机制,这些类都位于java.lang.reflect包中:

Class类:代表一个类。

Field 类:代表类的成员变量(成员变量也称为类的属性)。

Method类:代表类的方法。

Modifier类:代表修饰符。

lConstructor 类:代表类的构造方法。

Array类:提供了动态创建数组,以及访问数组的元素的静态方法。

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

public class Demo2 {
    public static void main(String[] args) {
        Student stu=new Student();
        Class clzStu= stu.getClass();
        //fields 拿到属性
        Field[] fields = clzStu.getDeclaredFields();
        System.out.println("fields"+Arrays.toString(fields));

        try {
            Field name = clzStu.getDeclaredField("name");
            System.out.println(name);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        //method 得到方法
        System.out.println("-------------------------");
        Method[] methods = clzStu.getDeclaredMethods();
        System.out.println(Arrays.toString(methods));

        try {
            Method ff = clzStu.getDeclaredMethod("ff", String.class);
             System.out.println(ff);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Method[] methods1 = clzStu.getMethods();
        System.out.println(Arrays.toString(methods1));


        //Modifiers 访问修饰符
        System.out.println("--------------------------");
        int modifiers = clzStu.getModifiers();
        System.out.println(modifiers);

        //Constructor 构造函数
        Constructor[] constructors = clzStu.getConstructors();
        System.out.println(Arrays.toString(constructors));

        try {
            Constructor anInt = clzStu.getConstructor();
            System.out.println(anInt);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        Constructor constructor = null;
        try {
            constructor = clzStu.getConstructor(int.class);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        System.out.println(constructor);

    }
}
public class Student {
    private String  name;
    private int glod;
    public Student(String name){
        this.name=name;
    }
    public Student(int glod){
        this.glod=glod;
    }
    private Student(String name,int glod){
        this.name=name;
        this.glod=glod;
    }

    @Override
    public String toString() {
        return "name:"+name+",glod:"+glod;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGlod() {
        return glod;
    }

    public void setGlod(int glod) {
        this.glod = glod;
    }
    public Student(){

    }
    public void ff(String xx){

    }
}

 

 

技术总结:

这些类都是在reflect反射包中提供的,这些类有助于我们获取类以及类中的属性,方法,访问修饰符,从而让我们能够得到类相关的具体信息.

只要你不跪着这个世界没人比你高 ! ! !

原文地址:https://www.cnblogs.com/KcBlog/p/13555517.html