反射从0到入门 (3)

运行结果:

public int com.javastudy.reflection.Fields.Student.score
public java.lang.String com.javastudy.reflection.Fields.Person.name
private int com.javastudy.reflection.Fields.Student.grade
获取 Field 的信息

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

getName():返回字段名称,例如:name

getType():返回字段类型,也是一个 Class 实例,例如:String.class

getModifiers():返回字段的修饰符,它是一个 int,不同的 bit 表示不同的含义。

The java.lang.reflect.Method.getModifiers() method returns the Java language modifiers for the method represented by this Method object, as an integer. The Modifier class should be used to decode the modifiers.

getmodifiers()方法以整数的形式返回该方法对象所表示的方法的 Java 语言修饰符。应该使用修饰词类来解码修饰词。

public class FieldTest2 {

    private final String name = "不是秃头的小李程序员";

    public static void main(String[] args) throws NoSuchFieldException {
        Class c = FieldTest2.class;
        Field field = c.getDeclaredField("name");
        int mod = field.getModifiers();
        System.out.println("name: " + field.getName());
        System.out.println("type: " + field.getType());
        System.out.println("final: " + Modifier.isFinal(mod));
        System.out.println("public: " + Modifier.isPublic(mod));
        System.out.println("protected: " + Modifier.isProtected(mod));
        System.out.println("private: " + Modifier.isPrivate(mod));
        System.out.println("static: " + Modifier.isStatic(mod));
    }
}

运行结果:

name: name
type: class java.lang.String
finaltrue
publicfalse
protectedfalse
privatetrue
staticfalse
获取字段值

我们拿到了 Field,该通过 Field 获取该字段对应的值。我们还是用上面的例子来获取 name 值。

public class FieldTest3 {

    private final String name = "不是秃头的小李程序员";

    public static void main(String[] args) throws Exception {
        Object object = new FieldTest3();
        Class c = FieldTest3.class;
        Field field = c.getDeclaredField("name");
        Object value = field.get(object);
        System.out.println(value);
    }
}

运行结果:

不是秃头的小李程序员

我们通过 get() 来获取 Field 的值,那么咱们在看一个下面的例子:

public class FieldTest4 {

    public static void main(String[] args) throws Exception 
        Object animal = new Animal("不是秃头的小李程序员 Animal111");
        Class c = Animal.class;
        Field field = c.getDeclaredField("name");
        Object value = field.get(animal);
        System.out.println(value);
//        Animal animal = new Animal();
//        animal.testFiled();
    }
}

class Animal {
    private String name;

    public Animal() {
    }

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

    public void testFiled() throws Exception {
        Object animal = new Animal("不是秃头的小李程序员 Animal222");
        Class c = Animal.class;
        Field field = c.getDeclaredField("name");
        Object value = field.get(animal);
        System.out.println(value);
    }
}

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zyfwdg.html