Get name of a field

后端 未结 7 969
日久生厌
日久生厌 2020-12-03 02:43

Is it possible in Java to get a name of field in string from the actual field? like:

public class mod {
    @ItemID
    public static ItemLinkTool linkTool;
         


        
7条回答
  •  悲&欢浪女
    2020-12-03 03:28

    I think this is what you are looking for.

    SomeClass data; // or List data; etc.
    List fieldNames = getFieldNamesForClass(data.get(0).getClass());
    
    private static List getFieldNamesForClass(Class clazz) throws Exception {
        List fieldNames = new ArrayList();
        Field[] fields = clazz.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            fieldNames.add(fields[i].getName());
        }
        return fieldNames;
    }
    

提交回复
热议问题