Deepak Mehra
Deepak Mehra

Reputation: 31

Parametrized Private Constructor using Reflection

How to access parametrized constructor using Reflection API. I have been trying to do it with the following set of class but it throws some error.

    //Primary class
    package com.deepak;

    public class A {
    private String name;

     private A(String name) {
            this.name = name;
        }

    }

//Exact class

    class MethodCall {

     Class first = Class.forName("com.deepak.A");
            Constructor constructor1 = first.getDeclaredConstructor();
            constructor1.setAccessible(true);
           A a= (A) constructor1.newInstance("deepak");
            System.out.println(a);


    }

Error message:

Exception in thread "main" java.lang.NoSuchMethodException: com.deepak.A.<init>()
    at java.lang.Class.getConstructor0(Class.java:3082)
    at java.lang.Class.getDeclaredConstructor(Class.java:2178)
    at com.deepak.MethodCall.main(MethodCall.java:44)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Upvotes: 1

Views: 943

Answers (2)

chengpohi
chengpohi

Reputation: 14217

This Exception means in relection it can't find constructor without param, since class A only have one constructor with accepting String param.

so you should getConstructor with your constructor parameter class, like:

 Constructor constructor1 = first.getConstructor(String.class);

Upvotes: 2

pamykyta
pamykyta

Reputation: 658

You could use following code to get what you need:

public static void main(String[] args) throws Exception {
    Class first = Class.forName("com.deepak.A");
    Constructor[] declaredConstructors = first.getDeclaredConstructors();
    Constructor constructor1 = declaredConstructors[0];
    constructor1.setAccessible(true);
    A a= (A) constructor1.newInstance("deepak");
    System.out.println(a);

}

Upvotes: 1

Related Questions