0

I'm having an issue with getting fields with private modifiers. I was under the understanding that getDeclaredFields() returned private fields versus getFields() which only returned public fields.

However when I attempt to log the amount of fields returned by getDeclaredFields() it returns 0.

Perhaps I do not understand how this aspect of reflection works?

@ConfigPopulate(value = "locale.no_permission", colour = true, format = true)
private String NO_PERMISSION_MESSAGE;

@ConfigPopulate(value = "locale.player_only_command", colour = true, format = true)
private String PLAYER_ONLY_COMMAND_MESSAGE;

@ConfigPopulate(value = "locale.incorrect_argument", colour = true, format = true)
private String INCORRECT_ARGUMENT_MESSAGE;

public MCommand(T instance, ConfigFile localeFile, String description, String permission, 

boolean playerOnlyCommand, String... aliases)
    {
        super(aliases[0], description, "", Lists.newLinkedList(Arrays.asList(aliases)));
        this.instance = instance;
        this.description = description;
        this.permission = permission;
        this.playerOnlyCommand = playerOnlyCommand;
        instance.getLogger().info("Fields: " + getClass().getDeclaredFields().length);
        localeFile.populate(this.getClass());
    }  

Result:

[14:28:45 INFO]: [MPrison] Fields: 0
  • 2
    Are you actually initializing a subclass by any chance? Try logging `getClass()` first. Note that `getDeclaredFields()` does *not* include inherited fields. – Jon Skeet Jan 06 '21 at 15:07
  • @JonSkeet Interesting. I logged the class and it output the packet and class name of the subclass extending the class shown above. Yet the code outputting the size of the list of declared fields is within the superclass. How can I access the fields within the superclass from the subclass without changing the field modifiers? – Duke Jake Morgan Jan 06 '21 at 15:15
  • Just use `MCommand.class.getDeclaredFields()` if you want the fields declared in `MCommand`. The `getClass()` method returns the *execution-time class* of an object (in this case the subclass) regardless of where the code is executed. – Jon Skeet Jan 06 '21 at 15:28

0 Answers0