我是靠谱客的博主 风趣金针菇,这篇文章主要介绍java 获取类中的字段值的方法,现在分享给大家,希望可以做个参考。

java获取字段值的方法。

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class BaseEntity<PK> implements Serializable { private PK test1; public PK getTest1() { return test1; } public void setTest1(PK test1) { this.test1 = test1; } } private static class Test extends BaseEntity<String> { private String test; public String getTest() { return test; } public void setTest(String test) { this.test = test; } }

1.通过内省:
必须要有get/set方法,才能读到,由于用反射获取值,故性能不高,只要有get/set方法,不考虑字段的修饰符,在spring中大多数采用的是内省复制
形如:

复制代码
1
2
3
4
<bean id="mySpringBootstrap" class="com.config.MySpringBootstrap"> <property name="bufferSize" value="4"></property> </bean>
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public final static <T> Object getField(String fieldName, T t) { Object invoke = null; try { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(fieldName, t.getClass()); Method readMethod = propertyDescriptor.getReadMethod(); readMethod.setAccessible(true); invoke = readMethod.invoke(t); return invoke; } catch (IntrospectionException | IllegalAccessException | InvocationTargetException e) { return invoke; } }

2.通过Field对象:
如果在所要查找的字段在父类中,需要递归去获取,而且还要设置可访问,私有字段和公共字段获取的方法不一样,需要自己判断,但是性能高。以下是获取私有字段的方法

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public final static <T> Object getFastField(String fieldName, T t) { Class<?> aClass = t.getClass(); do { try { Field field = aClass.getDeclaredField(fieldName); field.setAccessible(true); Object o = field.get(t); return o; } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) { aClass = aClass.getSuperclass(); } } while (aClass == Object.class); return null; }

最后

以上就是风趣金针菇最近收集整理的关于java 获取类中的字段值的方法的全部内容,更多相关java内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部