I have a situation where I can't change the main API of a set of classes, but I need to construct a new instance from archival data, including setting a large number of private fields.
My idea thus far was to create a static factory method that would produce my instance from the archival, like so:
Version 1:
public class Item { private Long id; public static Item fromArchived(final ArchivedItem archived) { return new Item(){{ this.id = archived.getId(); }}; } } IntelliJ IDEA gives me no red lines, I didn't have any idea there was an issue until I ran my maven build which yields:
error: id has private access in Item In contrast, this works:
Version 2:
public class Item { private Long id; public static Item fromArchived(final ArchivedItem archived) { Item item = new Item(){{ // this.id = archived.getId(); }}; item.id = archived.getId(); return item; } } I've been reviewing my core Java knowledge, and the only vague guess I have as to why Version 1 doesn't work is that the instance initializer (double brace initialization) somehow occurs in the static context, which doesn't really make sense either. Thoughts?
EDIT
I think the initial form of the question was vague. The answer I'm looking for is one which explains why I have visibility to the parent's private id field in the body of the static method but I lose visibility to it in the body of the instance initializer of the anonymous subclass inside that same static method.