How to get Java reflect to spot fields in the super class? not just the actual class [duplicate]

試著忘記壹切 提交于 2019-12-01 14:59:39

You can use this.getClass().getSuperClass() until this getSuperClass() method returns null to get the parent fields.

So, the best would be that you factorize your code. Implement one method that takes a list of Field as parameter and do your logical part within it, and a main method that search for fields through a while(superClass != null) loop.

mds404

Though it's late, I'm adding my suggestion since it's a nice solution.

Spring framework provide a nice Util class org.springframework.util.ReflectionUtils this class has several methods which we can use. To get a Field instance of an attribute from objectClass and superClasses I used ReflectionUtils.findField(clazz, fieldName);

Good thing with util is it doesn't throw an exception. Instead it returns null for invalid ones, so you can handle it gracefully.

Apache Commons Lang provides a method FieldUtils.getAllFields() which is an implementation of @sp00m's algorithm.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!