I was trying to override a method from some Gson api for custom json parsing. So I ended up stucked in a situation where I cann’t override a protected method from a Java class inside the build.gradle. I have tried running apart only the Groovy script and it works as it should.
For example, I’ve written a groovy script to do some very specific json parsing:
import java.io.IOException;
import java.io.Writer;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonWriter;
public class DescriptorJsonWriter {
def test (){
def dest = new File("c:/temp/", "descriptor.json")
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(dest));
JsonWriter jsonWriter = new JsonWriter(fileWriter) {
//this is the method not being overrided at all
@Override
protected void writeDeferredName() throws IOException {
println "custom writeDeferredName"
}
}
Gson gson = new GsonBuilder().create();
def descriptor = [ name: "abcbcbcbcbc"]
gson.toJson(descriptor, HashMap.class, jsonWriter);
jsonWriter.flush()
jsonWriter.close()
}
}
Then calling this like that:
task doTheParsing(){
dependsOn build
doLast {
generateDescriptor()
}
}
def generateDescriptor(){
DescriptorJsonWriter writer = new DescriptorJsonWriter()
writer.test()
}
and then:
>gradle doTheParsing
It gives the default implementation result of JsonWriter.writeDeferredName()
I tried to find something in the gradle documentation that explains such behavior, but I couldn’t find any.
The starting point here is that this could be a bug. Please share your thoughts about this issue