反射机制系列教材 (三)- 访问属性

通过反射机制修改对象的属性

步骤1:Hero.java
步骤2:TestRelection
步骤3:getField和getDeclaredField的区别

步骤 1 : Hero.java

为了访问属性,把name修改为public。
对于private修饰的成员,需要使用setAccessible(true)才能访问和修改。不在此知识点讨论。

package charactor;

public class Hero {

    public String name;

    public float hp;

    public int damage;

    public int id;

     

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public Hero(){

         

    }

    public Hero(String string) {

        name =string;

    }

    @Override

    public String toString() {

        return "Hero [name=" + name + "]";

    }

    public boolean isDead() {

        // TODO Auto-generated method stub

        return false;

    }

    public void attackHero(Hero h2) {

        System.out.println(this.name+ " 正在攻击 " + h2.getName());

    }

}

步骤 2 : TestRelection

通过反射修改属性的值

package reflection;

import java.lang.reflect.Field;

import charactor.Hero;

  

public class TestReflection {

  

    public static void main(String[] args) {

            Hero h =new Hero();

            //使用传统方式修改name的值为garen

            h.name = "garen";

            try {

                //获取类Hero的名字叫做name的字段

                Field f1= h.getClass().getDeclaredField("name");

                //修改这个字段的值

                f1.set(h, "teemo");

                //打印被修改后的值

                System.out.println(h.name);

                 

            catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

    }

}

步骤 3 : getField和getDeclaredField的区别

getField和getDeclaredField的区别
这两个方法都是用于获取字段
getField 只能获取public的,包括从父类继承来的字段。
getDeclaredField 可以获取本类所有的字段,包括private的,但是不能获取继承来的字段。 (: 这里只能获取到private的字段,但并不能访问该private字段的,除非加上setAccessible(true))


更多内容,点击了解: https://how2j.cn/k/reflection/reflection-attribute/110.html

原文地址:https://www.cnblogs.com/Lanht/p/12615437.html