zoukankan      html  css  js  c++  java
  • java中的反射技术系列四:反射类的字段

    ------------------------------------------------------------------------

    操作步骤:

    1、加载类,如Class cla=Person.class

    2、调用getField()/getDeclaredField()方法,参数是类的成员方法名称,如

    Filed Field f=cla.getDeclaredField("password");

    3、调用System.out.println(f.get(p));   

    --------------------------------------------------------------------------------

    例子:

    public class Person {
        public String name="qq";
        private int password=23;
        private  static int age=345;

    -----------------------------------------------------

    测试类:

    public class Demo2 {
        Person p = new Person();
    @Test
        public void demotest() throws Throwable, SecurityException {
            Class cla = Person.class;
            Field f=cla.getField("name");
            //获取字段的值
            Object value=f.get(p);
            //获取字段的类型
            Class type =f.getType();
            if(type.equals(String.class)){
                String svalue=(String)value;
                System.out.println(svalue);
            }
            //设置字段的值
            f.set(p,"你好");
            System.out.println(p.name);
            
            
        }
    @Test
    public void demotest2() throws Throwable, SecurityException {
        Class cla = Person.class;
        Field f=cla.getDeclaredField("password");
        f.setAccessible(true);
            System.out.println(f.get(p));
    }
    }

  • 相关阅读:
    小程序 视频
    b161: NOIP2007 4.Hanoi双塔问题
    命名规则、.gitignore、freopen()
    c++学习记录(九)
    c++学习笔记(八)
    2020面向对象程序设计寒假作业2
    c++学习记录(七)
    c++学习记录(六)
    c+学习记录(五)
    c++学习记录(四)
  • 原文地址:https://www.cnblogs.com/danyuzhu11/p/6170649.html
Copyright © 2011-2022 走看看