反射

程序在运行中过程中,对于任何一个类都能知道它所有的属性和方法,对于任意一个对象,都能知道调用它的任意属性和方法。

1.获得setter,getter方法

MyObject myObject = new MyObject();
//反射调用getter方法
Method getMethod = myObject.getClass().getMethod("get" + "MyPropValue");
String res = getMethod.invoke(myObject).toString();
//反射调用setter方法
Method method = myObject.getClass().getMethod("set" + "MyPropValue", String.class);
method.invoke(myObject, "Value");

2.常见使用方法

public class ReflectDemo {

    public static void main(String[] args) throws Exception {
        Class student = null;
        student = Class.forName("Student");

        // 获取公有属性
        Field[] fields = student.getFields();
        for(Field field : fields){
            System.out.println(field);
        }

        //获取所有属性 不包含继承的
        Field[] declaredFields = student.getDeclaredFields();
        for(Field df : declaredFields){
            System.out.println(df);
        }

        //获取所有公共方法
        Method[] methods = student.getMethods();
        for (Method method : methods){
            System.out.println(method);
        }

        //获取所有方法 不包含继承的
        Method[] declaredMethods = student.getDeclaredMethods();
        for (Method dm: declaredMethods){
            System.out.println(dm);
        }

        //获取所有公共构造方法
        Constructor[] constructors = student.getConstructors();

        //获取所有构造方法
        Constructor[] declaredConstructors = student.getDeclaredConstructors();

        //获取对象
        Class c = Class.forName("Student");
        Student student1 = (Student) c.newInstance();

        // 获取对象利用构造函数
        Constructor<Student> constructor = c.getConstructor(String.class, String.class);
        Student student2 = (Student) constructor.newInstance("lwx", "name");

        //获取方法
        Method method = c.getMethod("fun");
        Object object = method.invoke(student1);

    }
}

3.ClassLoader类

类装载器用来把类装载到JVM中,使用双亲委派模型来搜索加载类

posted @ 2023-08-16 19:04  lwx_R  阅读(3)  评论(0编辑  收藏  举报