Java之反射获取私有成员变量-yellowcong

来源:互联网 发布:qt淘宝公会 编辑:程序博客网 时间:2024/05/29 07:34

获取到对象的私有字段Field后,然后设定 setAccessible 为true,然后调用字段的get方法,就可以获取到对象的数据了,同时也可以通过反射的方法获取字段的get和set方法来获取需要修改的字段

/* * @version $Id$ * * Copyright (c) 2009-2010 yellowcong */package com.yellowcong.dao;import java.lang.reflect.Field;import jp.co.bsnnet.sofia.dto.keiyaku.wfgm1000.Wfgm1070FormCtlDto;import jp.co.bsnnet.sofia.utils.CtlField;import org.json.simple.JSONObject;/** * UserTest。 * * * * @version $Id$ */public class CopyOfUserTest {    public static void main(String [] args) throws Exception, SecurityException{        JSONObject obj = new JSONObject();        Wfgm1070FormCtlDto dto = new Wfgm1070FormCtlDto();        dto.getGrdKngaku1().setDisable(true);        dto.getGrdKngaku1().setDefaultValue("doubi");        //通过获取到字段,然后设定 setAccessible 为true,就可以访问私有变量了        Field field = Wfgm1070FormCtlDto.class.getDeclaredField("grdKngaku1");        field.setAccessible(true);        CtlField myfile =  (CtlField)field.get(dto);        System.out.println(myfile.isDisable()+myfile.getDefaultValue());        //通过set和get方法来设定值        CtlField myfile2=  (CtlField)Wfgm1070FormCtlDto.class.getMethod("getGrdKngaku1", null).invoke(dto, null);        System.out.println(myfile2.isDisable()+myfile2.getDefaultValue());    }}