用反射设置私有字段值

编程入门 行业动态 更新时间:2024-10-23 05:03:11
本文介绍了用反射设置私有字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有2个班级:Father和Child

public class Father implements Serializable, JSONInterface { private String a_field; //setter and getter here } public class Child extends Father { //empty class }

通过反射,我想在Child类中设置a_field:

With reflection I want to set a_field in Child class:

Class<?> clazz = Class.forName("Child"); Object cc = clazz.newInstance(); Field f1 = cc.getClass().getField("a_field"); f1.set(cc, "reflecting on life"); String str1 = (String) f1.get(cc.getClass()); System.out.println("field: " + str1);

但我有一个例外:

线程"main"中的异常java.lang.NoSuchFieldException:a_field

Exception in thread "main" java.lang.NoSuchFieldException: a_field

但是,如果我尝试:

Child child = new Child(); child.setA_field("123");

有效.

使用setter方法,我有同样的问题:

Using setter method I have same problem:

method = cc.getClass().getMethod("setA_field"); method.invoke(cc, new Object[] { "aaaaaaaaaaaaaa" });

推荐答案

要访问私有字段,您需要将Field::setAccessible设置为true.您可以离开超类领域.这段代码有效:

To access a private field you need to set Field::setAccessible to true. You can pull the field off the super class. This code works:

Class<?> clazz = Child.class; Object cc = clazz.newInstance(); Field f1 = cc.getClass().getSuperclass().getDeclaredField("a_field"); f1.setAccessible(true); f1.set(cc, "reflecting on life"); String str1 = (String) f1.get(cc); System.out.println("field: " + str1);

更多推荐

用反射设置私有字段值

本文发布于:2023-07-30 00:37:15,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1245002.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!