获取一个类所有属性

约定不等于承诺〃 2022-07-12 13:10 270阅读 0赞

1.需求场景

有时候一个类里面有很多的属性,我们需要把这些类的名字单独拎出来处理,比如说手动配置 mybatis 的 Mapper 文件,这个时候手动的去拷贝这些属性将会变得非常枯燥,这个时候我们可以使用一个类自动的帮我们把这些属性给获取出来,按照我们需要的格式给输出出来,这大大节省了我们自己的时间,而且不会出错。

2.一个测试类

  1. /** * Project Name:test * File Name:Test.java * Package Name:com.test.field * Date:2017年2月24日上午10:39:30 * */
  2. package com.test.field;
  3. /** * ClassName:Test <br/> * Date: 2017年2月24日 上午10:39:30 <br/> * @author ztd * @version * @see */
  4. public class Test {
  5. private int id;
  6. private String name;
  7. public int getId() {
  8. return id;
  9. }
  10. public void setId(int id) {
  11. this.id = id;
  12. }
  13. public String getName() {
  14. return name;
  15. }
  16. public void setName(String name) {
  17. this.name = name;
  18. }
  19. }

3.获取这个类所有属性的工具类

  1. /** * Project Name:test * File Name:GetField.java * Package Name:com.test.field * Date:2017年2月24日上午10:39:20 * */
  2. package com.test.field;
  3. import java.lang.reflect.Field;
  4. /** * ClassName:GetField <br/> * Date: 2017年2月24日 上午10:39:20 <br/> * @author ztd * @version * @see */
  5. public class GetFieldNamesUtils {
  6. public static void main(String[] args) {
  7. getFiledsNameWithBlankLine("com.test.field.Test");
  8. System.out.println("===================");
  9. getFiledsNameWithPoint("com.test.field.Test");
  10. }
  11. /** * 把属性通过换行的方式输出出来 * @author ztd * @param classPath */
  12. private static void getFiledsNameWithBlankLine(String classPath) {
  13. Class<?> clazz = null;
  14. try {
  15. clazz = Class.forName(classPath);
  16. } catch (ClassNotFoundException e) {
  17. e.printStackTrace();
  18. }
  19. Field[] fields = clazz.getDeclaredFields();
  20. for(Field f : fields) {
  21. System.out.println(f.getName());
  22. }
  23. }
  24. /** * 把属性通过“,”连接起来输出 * @author ztd * @param classPath */
  25. private static void getFiledsNameWithPoint(String classPath) {
  26. Class<?> clazz = null;
  27. try {
  28. clazz = Class.forName(classPath);
  29. } catch (ClassNotFoundException e) {
  30. e.printStackTrace();
  31. }
  32. Field[] fields = clazz.getDeclaredFields();
  33. StringBuffer sb = new StringBuffer();
  34. for(Field f : fields) {
  35. sb.append(f.getName()).append(",");
  36. }
  37. System.out.println(sb.toString());
  38. }
  39. }

4.效果:

  1. id
  2. name ===================
  3. id,name,

发表评论

表情:
评论列表 (有 0 条评论,270人围观)

还没有评论,来说两句吧...

相关阅读