File size: 2,361 Bytes
b27bfb3
 
 
 
1
2
3
4
5
{"type": "session", "harness": "opencode", "id": "lang-0041", "name": "Creating instances via reflection constructors"}
{"type": "message", "message": {"role": "system", "content": "You are an expert Java developer specializing in reflection, dynamic class loading, and modern Java APIs for runtime introspection."}}
{"type": "message", "message": {"role": "user", "content": "Show how to create instances of a class using reflection constructors. Include getConstructor, getDeclaredConstructor, and handling multiple constructors with different parameter types."}}
{"type": "message", "message": {"role": "assistant", "content": "Constructor reflection lets you create instances even when constructors are private.\n\n```java\nimport java.lang.reflect.Constructor;\n\npublic class ConstructorReflection {\n    private String value;\n    private int number;\n    public ConstructorReflection() { this.value = \"default\"; this.number = 0; }\n    public ConstructorReflection(String value) { this.value = value; this.number = 0; }\n    private ConstructorReflection(String value, int number) { this.value = value; this.number = number; }\n    @Override\n    public String toString() { return \"ConstructorReflection{value='\" + value + \"', number=\" + number + \"}\"; }\n    public static void main(String[] args) throws Exception {\n        Constructor<?> noArg = ConstructorReflection.class.getConstructor();\n        Object obj1 = noArg.newInstance();\n        System.out.println(obj1);\n        Constructor<?> strArg = ConstructorReflection.class.getConstructor(String.class);\n        Object obj2 = strArg.newInstance(\"hello\");\n        System.out.println(obj2);\n        Constructor<?> privateCtor = ConstructorReflection.class.getDeclaredConstructor(String.class, int.class);\n        privateCtor.setAccessible(true);\n        Object obj3 = privateCtor.newInstance(\"secret\", 42);\n        System.out.println(obj3);\n        Constructor<?>[] all = ConstructorReflection.class.getDeclaredConstructors();\n        System.out.println(\"Total constructors: \" + all.length);\n    }\n}\n```\nKey points: getConstructor only finds public constructors; getDeclaredConstructor finds any access level. setAccessible(true) is needed for non-public constructors. newInstance on a Constructor can throw InvocationTargetException if the constructor throws."}}