I have a class called Scraper with a static inner class Builder, and also a non-static inner class called StringPair, I’m trying to get one of the builder methods to construct a new StringPair(a,b) and add it to an ArrayList<StringPair>, however it doesn’t compile, the compiler says Error: non-static variable this cannot be referenced from a static context and specifically highlights the new StringPair(a,b) as the source of the problem.
I don’t understand what’s wrong here, any help would be appreciated!
class Scraper {
private final ArrayList<StringPair> stringPairs;
Scraper(Builder builder) {
stringPairs = builder.builderStringPairs;
}
public static class Builder {
private static ArrayList<StringPair> builderStringPairs = new ArrayList<StringPair>();
public Builder addStringPairs(String a, String b) {
builderStringPairs.add(new StringPair(a, b));
return this;
}
public Scraper build() {
return new Scraper(this);
}
}
class StringPair {
String a,b;
StringPair(String a, String b) {
this.a = a;
this.b = b;
}
String getA() {
return a;
}
String getB() {
return b;
}
}
}
Builderisn’t an inner class – it’s just a nested class, with no implicit reference to an instance of the containing class (Scraper).StringPair, however, is an inner class. In order to construct an instance ofStringPair, you need to have a reference to an instance ofScraper. So, options for makingBuilderwork:StringPaira nested class (static)Give
Builderan instance somewhere, at which point you could use:I suspect the second option is the most appropriate one here – I can’t see any reason why
StringPairneeds a reference to an instance ofScraper.See section 8.1.3 of the JLS for more information about nested and inner classes.