0
点赞
收藏
分享

微信扫一扫

21.反射-获取基本属性

young_d807 2022-02-03 阅读 66


instanceof不但匹配指定类型,还匹配指定类型的子类。而用 ==判断 class实例可以精确地判断数据类型,但不能作子类型比较。
==是精确匹配

调用Field.setAccessible(true)的意思是,别管这个字段是不是public,一律允许访问。

import java.lang.reflect.Field;

public class Main {

    public static void main(String[] args) throws Exception {
        Object p = new Person("Xiao Ming");
        Class c = p.getClass();
        Field f = c.getDeclaredField("name");
        f.setAccessible(true);
        Object value = f.get(p);
        System.out.println(value); // "Xiao Ming"
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }
}

public class Main {

    public static void main(String[] args) throws Exception {
        Person p = new Person("Xiao Ming");
        System.out.println(p.getName()); // "Xiao Ming"----公共方法
        Class c = p.getClass();//反射
        Field f = c.getDeclaredField("name");
        f.setAccessible(true);
        f.set(p, "Xiao Hong");
        System.out.println(p.getName()); // "Xiao Hong"
        //修改非public字段,需要首先调用setAccessible(true)。
    }
}

class Person {
    private String name;

    public Person(String name) {
        this.name = name;
    }

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

一个 Field对象包含了一个字段的所有信息:

 

小结

Java的反射API提供的 Field类封装了字段的所有信息:

举报

相关推荐

0 条评论