You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写方法获取任意对象(如实体类)的所有字段名称

How to Get All Field Names from Any Object in Java

Got it, let's solve this problem! You need a method that takes any object (like your Human entity class) and returns all its field names in the format [name,fam,patr]. The standard way to do this in Java is using reflection—it lets us inspect a class's metadata at runtime, including its fields.

Step-by-Step Implementation

Here's a complete, working method that does exactly what you need:

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

public class FieldExtractor {
    public String getFieldsTitle(Object obj) {
        // Guard against null input to avoid NullPointerException
        if (obj == null) {
            return "[]";
        }
        
        // Get the class of the input object
        Class<?> objClass = obj.getClass();
        // Retrieve ALL declared fields (including private ones)
        Field[] allFields = objClass.getDeclaredFields();
        
        List<String> fieldNames = new ArrayList<>();
        // Collect each field's name
        for (Field field : allFields) {
            fieldNames.add(field.getName());
        }
        
        // Convert the list to your desired compact format (remove spaces)
        return fieldNames.toString().replaceAll("\\s", "");
    }
}

Let's Break Down the Code

  • Null Check: First, we handle the case where the input object is null—returning an empty array string instead of crashing.
  • Class Instance: obj.getClass() gives us the Class object representing the input's type, which we need to access its fields.
  • Get Declared Fields: We use getDeclaredFields() instead of getFields() because the latter only returns public fields. Your Human class has private fields, so this is crucial.
  • Collect Names: We loop through each Field object and add its name to a list.
  • Format Output: The default List.toString() gives [name, fam, patr], so we remove spaces with replaceAll("\\s", "") to get the compact [name,fam,patr] format.

Test It with Your Human Class

Let's verify this works with your example Human class:

public class Human {
    private String name;
    private String fam;
    private String patr;
    // Getters/setters aren't needed here since we're only reading field names
}

// Test the method
public class Main {
    public static void main(String[] args) {
        Human person = new Human();
        FieldExtractor extractor = new FieldExtractor();
        
        String result = extractor.getFieldsTitle(person);
        System.out.println(result); // Output: [name,fam,patr]
    }
}

Bonus: Include Parent Class Fields

If you need to include fields from parent classes (not just the immediate class), you can modify the method to traverse the class hierarchy:

public String getFieldsTitleIncludingParents(Object obj) {
    if (obj == null) {
        return "[]";
    }
    
    List<String> fieldNames = new ArrayList<>();
    Class<?> currentClass = obj.getClass();
    
    // Traverse up to the Object class (stop before it)
    while (currentClass != null && !currentClass.equals(Object.class)) {
        Field[] fields = currentClass.getDeclaredFields();
        for (Field field : fields) {
            fieldNames.add(field.getName());
        }
        // Move to the parent class
        currentClass = currentClass.getSuperclass();
    }
    
    return fieldNames.toString().replaceAll("\\s", "");
}

Important Notes

  • Accessibility: We don't need to call field.setAccessible(true) here because we're only reading field names, not their values. If you ever need to access field values, you'd need that line to bypass private access restrictions.
  • Performance: Reflection is slower than direct code access. Avoid using this in performance-critical sections of your application if possible.
  • Security: In environments with strict security managers, reflection access might be restricted. Make sure your runtime allows it.

内容的提问来源于stack exchange,提问作者Vytsalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 09:11:22