1

I want to avoid the constructor calling during object creation in java (either default constructor or user defined constructor) . Is it possible to avoid constructor calling during object creation???

Thanks in advance......

3
  • 4
    Can you give a little more background? Why do you want to do that? Commented Feb 13, 2013 at 11:37
  • 1
    Simple answer: No, it's not possible. Commented Feb 13, 2013 at 11:40
  • do you want to prevent users of your class to do new MyClass() and/or new MyClass(args...) ? is that what you mean ? Commented Feb 13, 2013 at 11:41

4 Answers 4

2

Simply extract the intialization logic that you want to avoid into another method called init. You can not avoid calling exactly one constructor.

Sign up to request clarification or add additional context in comments.

Comments

2

No matter what pattern or strategy you use, at some point your will need to call a constructor if you want to create an object.

Comments

0

Actually, its possible under some circumstances by using classes from the JVM implementation (which do not belong to the JRE API and are implemenation specific).

One example here http://www.javaspecialists.eu/archive/Issue175.html

It should also be possible using sun.misc.Unsafe.allocateInstance() (Java7)

Also, the constructor is apparently bypassed when using the clone()-method to create a copy of an object (and the class doesn't override clone to implement it different from the Object.clone() method).

All of these possibilities come with strings attached and should be used carefully, if at all.

Comments

0

You can mock the constructors of a class. They will still be called, but not executed. For example, the following JUnit+JMockit test does that:

static class CodeUnderTest
{
    private final SomeDependency someDep = new SomeDependency(123, "abc");

    int doSomething(String s)
    {
        someDep.doSomethingElse(s);
        return someDep.getValue(); 
    }
}

static final class SomeDependency
{
    SomeDependency(int i, String s) { throw new RuntimeException("won't run"); }
    int getValue() { return -1; }
}

@Test
public void mockEntireClassIncludingItsConstructors()
{
    new NonStrictExpectations() {
        @Mocked SomeDependency mockDep;
        { mockDep.getValue(); result = 123; }
    };

    int result = new CodeUnderTest().doSomething("testing");

    assertEquals(123, result);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.