How can I access the private class constructor?

I am a Java developer. In an interview I was asked a question about private designers:

Is it possible to access the private constructor of a class and instantiate it?

I answered no, but I was wrong.

Can you explain why I was wrong and give an example of creating an object using a private constructor?

+63
java constructor oop instance
Apr 08 2018-10-10T00:
source share
19 answers

One way around the limitation is to use reflections:

import java.lang.reflect.Constructor; public class Example { public static void main(final String[] args) throws Exception { Constructor<Foo> constructor = Foo.class.getDeclaredConstructor(); constructor.setAccessible(true); Foo foo = constructor.newInstance(); System.out.println(foo); } } class Foo { private Foo() { // private! } @Override public String toString() { return "I'm a Foo and I'm alright!"; } } 
+79
Apr 08 '10 at 11:40
source share
  • You can access it inside the class itself (for example, in the public static factory method)
  • If it is a nested class, you can access it from the wrapper class
  • If you have the appropriate permissions, you can access it with a reflection

It is not clear whether any of them is applicable - can you provide additional information?

+67
Apr 08 '10 at
source share

This can be achieved by reflection.

Consider for the Test class using a private constructor:

 Constructor<?> constructor = Test.class.getDeclaredConstructor(Context.class, String[].class); Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers())); constructor.setAccessible(true); Object instance = constructor.newInstance(context, (Object)new String[0]); 
+19
Apr 08 '10 at
source share

The very first question asked about private designers in an interview:

Can we have a private constructor in the class?

And sometimes the candidate gives the answer: no, we cannot have private designers.

So I would like to say: yes, you can have private constructors in the class.

This is not a special thing, try to think so

Private: everything that is private is accessible only from the class.

Constructor: a method whose name matches the name of the class, and it is implicitly called when the class object is created.

or you can say that to create an object you need to call its constructor, if the constructor is not called, then the object cannot be created.

This means that if we have a private constructor in the class, then its objects can only be created inside the class. Thus, in simple terms, if the constructor is private, you cannot create its objects outside the class.

What are the benefits? This concept can be implemented to achieve a singleton object (this means that only one class object can be created).

See the following code,

 class MyClass{ private static MyClass obj = new MyClass(); private MyClass(){ } public static MyClass getObject(){ return obj; } } class Main{ public static void main(String args[]){ MyClass o = MyClass.getObject(); //The above statement will return you the one and only object of MyClass //MyClass o = new MyClass(); //Above statement (if compiled) will throw an error that you cannot access the constructor. } } 

Now the tricky part is why you made a mistake, as explained in other answers, you can get around the limitation using Reflection.

+6
Jun 23 '14 at 10:24
source share

Using java reflection as follows:

  import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; class Test { private Test() //private constructor { } } public class Sample{ public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException { Class c=Class.forName("Test"); //specify class name in quotes //----Accessing private constructor Constructor con=c.getDeclaredConstructor(); con.setAccessible(true); Object obj=con.newInstance(); } } 
+4
Jun 09 '16 at 12:46 on
source share

I like the answers above, but there are two more great ways to create a new instance of a class that has a private constructor. It all depends on what you want to achieve and under what circumstances.

1: Using Java and ASM tools

In this case, you need to start the JVM with a transformer. To do this, you need to implement a new Java agent, and then make this transformer to change the constructor for you.

First create a class transformer. This class has a method called conversion. Override this method and inside this method you can use the ASM reader class and other classes to control the visibility of your constructor. After the transformer is completed, your client code will have access to the constructor.

You can read more about this here: Modifying a private Java constructor with ASM

2: rewrite the constructor code

Well, actually this is not a call to the constructor, but you can create an instance. Suppose you are using a third-party library (say Guava) and you have access to the code, but you do not want to change this code in the bank, which is loaded by the JVM for some reason (I know this is not very realistic, but let the code is in a common container, such as Jetty, and you cannot change the general code, but you have a separate context for loading classes), then you can make a copy of the third-party code using a private constructor, change the private constructor, protected or open in your code and then put your class at the beginning of the class path m From now on, your client can use the modified constructor and create instances.

This last change is called the link seam , which is a kind of seam where the inclusion point is the class path.

+4
Jul 02 '16 at 0:44
source share

Yes, you could, as @Jon Steet mentioned.

Another way to access the private constructor is to create a public static method in this class and its return type as its object.

 public class ClassToAccess { public static void main(String[] args) { { ClassWithPrivateConstructor obj = ClassWithPrivateConstructor.getObj(); obj.printsomething(); } } } class ClassWithPrivateConstructor { private ClassWithPrivateConstructor() { } public void printsomething() { System.out.println("HelloWorld"); } public static ClassWithPrivateConstructor getObj() { return new ClassWithPrivateConstructor(); } } 
+3
Jun 25 '14 at 4:58
source share

Of course, you can access the private constructor from other methods or constructors in the same class and its inner classes. Using reflection, you can also use a private constructor elsewhere, provided that the SecurityManager does not stop you from doing this.

+2
Apr 08 '10 at
source share

Yes, we can access the private constructor or create an instance of the class using the private constructor. The java reflection APIs and Singleton design pattern make extensive use of the concept to access a private constructor. In addition, Spring framework containers can access a private bean constructor, and this framework uses the java reflection API. The following code demonstrates how to access a private constructor.

 class Demo{ private Demo(){ System.out.println("private constructor invocation"); } } class Main{ public static void main(String[] args){ try{ Class class = Class.forName("Demo"); Constructor<?> con = string.getDeclaredConstructor(); con.setAccessible(true); con.newInstance(null); }catch(Exception e){} } } output: private constructor invocation 

I hope you got it.

+2
Jul 10 '17 at 18:49
source share

Yes, you can instantiate an instance using a private constructor using Reflection , see the example that was inserted below, taken from java2s , to understand how:

 import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; class Deny { private Deny() { System.out.format("Deny constructor%n"); } } public class ConstructorTroubleAccess { public static void main(String... args) { try { Constructor c = Deny.class.getDeclaredConstructor(); // c.setAccessible(true); // solution c.newInstance(); // production code should handle these exceptions more gracefully } catch (InvocationTargetException x) { x.printStackTrace(); } catch (NoSuchMethodException x) { x.printStackTrace(); } catch (InstantiationException x) { x.printStackTrace(); } catch (IllegalAccessException x) { x.printStackTrace(); } } } 
0
Jun 30 '16 at 19:23
source share

The main premise of having a private constructor is that having a private constructor limits the access of code other than the code of your own class from creating objects of this class.

Yes, we can have private constructors in the class, and yes, they can be accessed by creating some static methods, which in turn will create a new object for the class.

  Class A{ private A(){ } private static createObj(){ return new A(); } Class B{ public static void main(String[]args){ A a=A.createObj(); }} 

So, to create an object of this class, another class must use static methods.

What is the meaning of the static method when creating a private constructor?

Static methods exist so that if you need to instantiate this class, then there may be some predefined checks that can be applied to static methods before instantiating. For example, in the Singleton class, a static method checks to see if an instance has already been created or not. If an instance has already been created, it simply simply returns that instance, rather than creating a new one.

  public static MySingleTon getInstance(){ if(myObj == null){ myObj = new MySingleTon(); } return myObj; } 
0
Feb 25 '17 at 20:50
source share

I hope this example can help you:

 package MyPackage; import java.lang.reflect.Constructor; /** * @author Niravdas */ class ClassWithPrivateConstructor { private ClassWithPrivateConstructor() { System.out.println("private Constructor Called"); } } public class InvokePrivateConstructor { public static void main(String[] args) { try { Class ref = Class.forName("MyPackage.ClassWithPrivateConstructor"); Constructor<?> con = ref.getDeclaredConstructor(); con.setAccessible(true); ClassWithPrivateConstructor obj = (ClassWithPrivateConstructor) con.newInstance(null); }catch(Exception e){ e.printStackTrace(); } } } 

Conclusion: the private constructor is called

0
Jan 08 '19 at 6:44
source share

We cannot access the private constructor outside the class, but using the Java Reflection API, we can access the private constructor. Please find below code:

 public class Test{ private Test() System.out.println("Private Constructor called"); } } public class PrivateConsTest{ public void accessPrivateCons(Test test){ Field[] fields = test.getClass().getDeclaredFields(); for (Field field : fields) { if (Modifier.isPrivate(field.getModifiers())) { field.setAccessible(true); System.out.println(field.getName()+" : "+field.get(test)); } } } } 

If you use Spring IoC, the Spring container also creates and embeds a class object that has a private constructor.

0
Jan 09 '19 at 13:04
source share

I tried how it works. Give me a suggestion if I am wrong.

 import java.lang.reflect.Constructor; class TestCon { private TestCon() { System.out.println("default constructor...."); } public void testMethod() { System.out.println("method executed."); } } class TestPrivateConstructor { public static void main(String[] args) { try { Class testConClass = TestCon.class; System.out.println(testConClass.getSimpleName()); Constructor[] constructors = testConClass.getDeclaredConstructors(); constructors[0].setAccessible(true); TestCon testObj = (TestCon) constructors[0].newInstance(); //we can call method also.. testObj.testMethod(); } catch (Exception e) { e.printStackTrace(); } } } 
0
Jan 10 '19 at 9:09
source share

The simple answer is yes, we can have private constructors in Java .

There are various scenarios in which we can use private constructors. The main ones

  • Constructor Inner Chain
  • Singleton class design pattern
0
Jan 11 '19 at 8:32
source share

Reflection is an API in java that we can use to call methods at runtime regardless of the access specifier used with them. To access the private class constructor:

My utility class

 public final class Example{ private Example(){ throw new UnsupportedOperationException("It is a utility call"); } public static int twice(int i) { int val = i*2; return val; } } 

My Test class which creates an object of the Utility class(Example)

 import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; class Test{ public static void main(String[] args) throws Exception { int i =2; final Constructor<?>[] constructors = Example.class.getDeclaredConstructors(); constructors[0].setAccessible(true); constructors[0].newInstance(); } } 

When calling the constructor, it will throw a java.lang.UnsupportedOperationException: It is a utility call

But remember that using reflection APIs causes problems with overhead

0
Jul 22 '19 at 19:38
source share

Take a look at the Singleton template. It uses a private constructor.

-one
Apr 08 '10 at
source share

Well, you can also if there are other public constructors. Just because a constructor without parameters is private does not mean that you simply cannot create an instance of the class.

-2
Apr 08 2018-10-10T00:
source share

you can access it outside the class, it is very easy to access it just take an example of the singaltan class, we all do the same thing as the private constructor and access the instance using the static method, here is the code related to your request

 ClassWithPrivateConstructor.getObj().printsomething(); 

it will definitely work because i already tested

-3
Dec 11 '15 at 7:11
source share



All Articles