[Java基础]反射获取成员变量并使用练习

Posted Wecccccccc

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Java基础]反射获取成员变量并使用练习相关的知识,希望对你有一定的参考价值。

在这里插入图片描述

代码如下:

package ClassObjectPack;

public class Student {
    private String name;
    int age;
    public String address;

    public Student(String name, int age, String address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    public Student() {
    }

    private Student(String name) {
        this.name = name;
    }

    Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private void function()
    {
        System.out.println("function");
    }

    public void method1()
    {
        System.out.println("method");
    }

    public void method2(String s)
    {
        System.out.println("method:"+s);
    }

    public String method3(String s,int i)
    {
        return s+","+i;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\\'' +
                ", age=" + age +
                ", address='" + address + '\\'' +
                '}';
    }
}

package ClassObjectPack01;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo04 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        Class<?> c = Class.forName("ClassObjectPack.Student");

        Constructor<?> con = c.getConstructor();
        Object obj = con.newInstance();

        System.out.println(obj);

        //getField只能拿公共的
//        Field nameFiled = c.getField("name");

        Field nameField = c.getDeclaredField("name");

        nameField.setAccessible(true);

        nameField.set(obj,"林青霞");

        System.out.println(obj);

        System.out.println("--------------------------");

        //s.age = 30

        Field ageField = c.getDeclaredField("age");
        ageField.setAccessible(true);

        ageField.set(obj,30);

        System.out.println(obj);

        Field addressField = c.getDeclaredField("address");
        addressField.setAccessible(true);//可有可无

        addressField.set(obj,"西安");

        System.out.println(obj);

    }

}

测试结果:

在这里插入图片描述

以上是关于[Java基础]反射获取成员变量并使用练习的主要内容,如果未能解决你的问题,请参考以下文章

[Java基础]反射获取成员变量并使用

[Java基础]反射获取构造方法并使用练习

[Java基础]反射获取成员方法并使用

Java反射机制详解

JAVA基础知识之JVM-——使用反射生成并操作对象

二刷java基础第二十二天——反射