我是靠谱客的博主 留胡子小鸭子,最近开发中收集的这篇文章主要介绍java reflection set,How to set field values using Java reflection,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

In the Java reflection API, the java.lang.reflect.Field class represents a generic field in a class or interface, and allows to retrieve programmatically field information, such as name, type, or annotations. In addition, via the Field class we can get and set the value of a field in a given object.

The most generic method to set a field value is set(Object obj, Object value): it takes as first argument the object on which the field needs to be set, and as second argument the value for the field. The above method can be used for any field type, either primitive or class type; in case of a primitive type, value must be an instance of the Java class corresponding to the type, such as java.lang.Integer, java.lang.Float, and so on. For primitive types, there also exist specific methods that can be called passing them directly primitive type values:

·         setBoolean(Object obj, boolean z)

·         setByte(Object obj, byte b)

·         setChar(Object obj, char c)

·         setDouble(Object obj, double d)

·         setFloat(Object obj, float f)

·         setInt(Object obj, int i)

·         setLong(Object obj, long l)

·         setShort(Object obj, short s)

As with the generic set() method, in all the methods in the above list the first argument is the object whose field needs to be set and the second argument indicates the value for the field.

In the example below, we create an object of the java.awt.Rectangleclass and then set field values in that object by using the setInt() method; to verify that field values are actually set, we retrieve these values, using the getInt(Object obj) method of the Field class, before and after setting them.

import java.awt.*;import java.lang.reflect.*;public class SetFieldValueExample { public static void main(String[] args) throws Exception { Rectangle rect = new Rectangle(); Field xField = rect.getClass().getField("x"); Field yField = rect.getClass().getField("y"); Field widthField = rect.getClass().getField("width"); Field heightField = rect.getClass().getField("height"); System.out.println("---->> Before setting values <> After setting values <

The output of the above program demonstrates that all four field values have been correctly set:

---->> Before setting values <

x field value: 0

y field value: 0

width field value: 0

height field value: 0

---->> After setting values <

x field value: 10

y field value: 20

width field value: 40

height field value: 80

最后

以上就是留胡子小鸭子为你收集整理的java reflection set,How to set field values using Java reflection的全部内容,希望文章能够帮你解决java reflection set,How to set field values using Java reflection所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(38)

评论列表共有 0 条评论

立即
投稿
返回
顶部