{"record":{"id":"6edc350391a679b7","repo":"elastic/elasticsearch","slug":"cannot-access-method-field-name-from-a-null-def","errorCode":null,"errorMessage":"cannot access method/field [name] from a null def reference","messagePattern":"cannot access method/field \\[name\\] from a null def reference","errorType":"exception","errorClass":"NullPointerException","httpStatus":null,"severity":"error","filePath":"modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java","lineNumber":143,"sourceCode":"            this.functions = functions;\n            this.constants = constants;\n            this.methodHandlesLookup = methodHandlesLookup;\n            this.name = name;\n            this.flavor = flavor;\n            this.args = args;\n            this.depth = initialDepth;\n\n            MethodHandle fallback = FALLBACK.bindTo(this).asCollector(Object[].class, type.parameterCount()).asType(type);\n\n            setTarget(fallback);\n        }\n\n        /**\n         * guard method to give a more descriptive error message when a def receiver is null\n         */\n        static Class<?> checkNull(Object receiver, String name) {\n            if (receiver == null) {\n                throw new NullPointerException(\"cannot access method/field [\" + name + \"] from a null def reference\");\n            }\n\n            return receiver.getClass();\n        }\n\n        /**\n         * guard method for inline caching: checks the receiver's class is the same\n         * as the cached class\n         */\n        static boolean checkClass(Class<?> clazz, Object receiver) {\n            return receiver != null && receiver.getClass() == clazz;\n        }\n\n        /**\n         * Does a slow lookup against the whitelist.\n         */\n        private MethodHandle lookup(int flavorValue, String nameValue, Class<?> receiver) throws Throwable {\n            return switch (flavorValue) {","sourceCodeStart":125,"sourceCodeEnd":161,"githubUrl":"https://github.com/elastic/elasticsearch/blob/db6a809a667c081ca1dc7500389d26975573215f/modules/lang-painless/src/main/java/org/elasticsearch/painless/DefBootstrap.java#L125-L161","documentation":"In def mode, every method invocation and field access goes through a guard that checks whether the receiver is null. The checkNull guard fires a NullPointerException with the method/field name when the receiver is null, because there is no class to dispatch against. This provides a clearer diagnostic than a raw NPE from the JVM.","triggerScenarios":"A Painless script calls a method or accesses a field on a def variable that is null at runtime. Example: `def x = doc['optional_field'].value; def upper = x.toUpperCase();` where optional_field does not exist in the document, causing value to be null.","commonSituations":"Accessing a document field that is missing from some documents (Painless returns null for absent fields in def mode). Chaining calls on the result of a map lookup whose key may not exist. Processing heterogeneous documents where fields are conditionally present.","solutions":["Null-check before any method or field access: `if (x != null) { def upper = x.toUpperCase(); }`","Check field existence first: use `doc.containsKey('field')` or `doc['field'].size() != 0` before accessing the value.","Provide a default: `def x = doc['field'].value; if (x == null) { x = 'default'; }`","Avoid def for fields known to be absent; use typed accessors that return Optional-like semantics."],"exampleFix":"// before\ndef name = doc['display_name'].value;\ndef upper = name.toUpperCase();\n\n// after\ndef name = doc['display_name'].value;\nif (name != null) {\n    def upper = name.toUpperCase();\n} else {\n    def upper = '';\n}","handlingStrategy":"validation","validationCode":"// Painless: null-check before any method/field access on a def value\ndef x = doc['optional_field'].value;\nif (x != null) {\n    def result = x.toUpperCase();\n} else {\n    def result = '';\n}","typeGuard":"// Painless null guard\ndef safeAccess(def value, def defaultValue) {\n    return value != null ? value : defaultValue;\n}","tryCatchPattern":null,"preventionTips":["Always check `doc['field'].size() != 0` or `doc.containsKey('field')` before accessing field values that may be absent.","Establish a null-check convention for every def-typed variable derived from document fields.","Use explicit types (e.g., String, int) instead of def so missing fields surface as a compile-time mismatch rather than a runtime NPE."],"tags":["painless","def-type","null-reference","runtime","guard"],"analyzedSha":"db6a809a667c081ca1dc7500389d26975573215f","analyzedAt":"2026-08-12T01:39:14.192Z","schemaVersion":2},"datasetVersion":"2026-08-12T12:17:08.281Z"}