{"record":{"id":"bc6768a44ec48073","repo":"karatelabs/karate","slug":"tobean-needs-two-arguments-object-and-class-name","errorCode":null,"errorMessage":"toBean() needs two arguments: object and class name","messagePattern":"toBean\\(\\) needs two arguments: object and class name","errorType":"exception","errorClass":"RuntimeException","httpStatus":null,"severity":"error","filePath":"karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java","lineNumber":524,"sourceCode":"    @SuppressWarnings(\"unchecked\")\n    private static int compareKeys(Object a, Object b) {\n        if (a == null || b == null) {\n            return a == b ? 0 : (a == null ? -1 : 1);\n        }\n        if (a instanceof Number && b instanceof Number) {\n            return Double.compare(((Number) a).doubleValue(), ((Number) b).doubleValue());\n        }\n        if (a instanceof Comparable && a.getClass().isInstance(b)) {\n            return ((Comparable<Object>) a).compareTo(b);\n        }\n        // last resort for mixed or non-comparable keys, at least the order is stable\n        return String.valueOf(a).compareTo(String.valueOf(b));\n    }\n\n    static JavaInvokable toBean() {\n        return args -> {\n            if (args.length < 2) {\n                throw new RuntimeException(\"toBean() needs two arguments: object and class name\");\n            }\n            Object obj = args[0];\n            String className = args[1].toString();\n            // Convert to JSON string and deserialize to the target class\n            String jsonString = Json.of(obj).toString();\n            return Json.fromJson(jsonString, className);\n        };\n    }\n\n    /**\n     * Convert a list of maps to CSV string.\n     * Usage: karate.toCsv([{a:1,b:2},{a:3,b:4}]) => \"a,b\\n1,2\\n3,4\\n\"\n     */\n    @SuppressWarnings(\"unchecked\")\n    static JavaInvokable toCsv() {\n        return args -> {\n            if (args.length == 0 || args[0] == null) {\n                return \"\";","sourceCodeStart":506,"sourceCodeEnd":542,"githubUrl":"https://github.com/karatelabs/karate/blob/a22eb90246d958d15a47bf436693d0121ad2812d/karate-core/src/main/java/io/karatelabs/core/KarateJsUtils.java#L506-L542","documentation":"karate.toBean() converts a JS/Map object to an instance of a named Java class by serializing it to JSON and deserializing with Json.fromJson into the target class. The library requires exactly this pair — the object and the class name string — so it throws when fewer than two arguments are supplied. Without both, conversion is impossible since neither the data nor the target type is known.","triggerScenarios":"karate.toBean() with zero or one argument, e.g. karate.toBean(someMap) forgetting the class name, or karate.toBean('com.example.User') forgetting the object.","commonSituations":"Bridging JS objects to Java POJOs for Java interop in tests; copying old call signatures where the class name was previously inferred; typos after refactoring the helper's arity.","solutions":["Supply both arguments: karate.toBean(obj, 'com.example.MyClass') with the fully qualified class name as a string.","Ensure the first argument is the object (Map) and the second is the class name string — order matters.","If the object may be null, still pass it explicitly so the call has two arguments."],"exampleFix":"// before\nvar user = karate.toBean(response)\n// after\nvar user = karate.toBean(response, 'com.example.User')","handlingStrategy":"validation","validationCode":"if (obj == null || typeof className !== 'string' || className.indexOf('.') < 0) { throw new Error('toBean(obj, fullyQualifiedClassName) requires an object and a class name string') }","typeGuard":"function canToBean(obj, className) { return obj != null && typeof className === 'string' && className.length > 0 }","tryCatchPattern":"try { var bean = karate.toBean(obj, 'com.example.User') } catch (e) { if (('' + e).indexOf('needs two arguments') >= 0) { karate.logger.warn('toBean misused: need object + class name'); bean = null } throw e }","preventionTips":["Always pass the fully qualified class name as a string","Keep object-first, class-name-second argument order","Wrap toBean calls in a small helper function so arity mistakes surface in one place"],"tags":["javascript","argument-validation","java-interop"],"backgroundTag":"missing-required-argument","analyzedSha":"a22eb90246d958d15a47bf436693d0121ad2812d","analyzedAt":"2026-09-12T09:01:00.220Z","contentChangedAt":"2026-09-12T09:01:00.220Z","schemaVersion":2},"datasetVersion":"2026-09-16T19:17:19.609Z"}